import { expect, test } from "@playwright/test";
import { apiRequest } from "./api.js";
import { expectId, readJsonSafe } from "./generalFixtures.js";
import {
  CRUDFORM_EXTENSION_TESTS_DISABLED_ENV,
  crudFormExtensionTestsDisabled,
  getCustomFieldValue
} from "./crudFormFields.js";
function skipIfCrudFormExtensionTestsDisabled() {
  test.skip(
    crudFormExtensionTestsDisabled(),
    `${CRUDFORM_EXTENSION_TESTS_DISABLED_ENV} is set \u2014 CrudForm field-persistence sweep skipped`
  );
}
function assertScalarFieldsPersisted(record, expected, label = "record") {
  for (const [key, value] of Object.entries(expected)) {
    expect(record[key], `${label}.${key} should persist`).toEqual(value);
  }
}
function assertCustomFieldsPersisted(record, expected, label = "record") {
  for (const [name, value] of Object.entries(expected)) {
    expect(getCustomFieldValue(record, name), `${label} custom field "${name}" should persist`).toEqual(value);
  }
}
async function safeText(response) {
  try {
    return (await response.text()).slice(0, 500);
  } catch {
    return "<unreadable body>";
  }
}
async function defaultReadById(request, token, collectionPath, id) {
  const separator = collectionPath.includes("?") ? "&" : "?";
  const response = await apiRequest(
    request,
    "GET",
    `${collectionPath}${separator}id=${encodeURIComponent(id)}&page=1&pageSize=100`,
    { token }
  );
  expect(response.status(), `read-back ${collectionPath} failed: ${response.status()}`).toBe(200);
  const body = await readJsonSafe(response);
  if (Array.isArray(body?.items)) {
    return body.items.find((item) => item.id === id) ?? null;
  }
  return body && body.id === id ? body : null;
}
async function runCrudFormRoundTrip(config) {
  const { request, token, collectionPath } = config;
  const read = config.readById ?? ((id2) => defaultReadById(request, token, collectionPath, id2));
  let id = null;
  try {
    const createResponse = await apiRequest(request, "POST", collectionPath, {
      token,
      data: config.create.payload
    });
    expect(
      createResponse.status(),
      `create ${collectionPath} failed (${createResponse.status()}): ${await safeText(createResponse)}`
    ).toBe(config.create.expectedStatus ?? 201);
    const createBody = await readJsonSafe(createResponse) ?? {};
    const rawId = config.idFromCreate ? config.idFromCreate(createBody) : createBody.id ?? createBody.entityId;
    id = expectId(rawId, `create response should include an id (${collectionPath})`);
    const afterCreate = await read(id);
    expect(afterCreate, `created record ${id} should be readable from ${collectionPath}`).toBeTruthy();
    if (config.expectAfterCreate.scalars) {
      assertScalarFieldsPersisted(afterCreate, config.expectAfterCreate.scalars, "after-create");
    }
    if (config.expectAfterCreate.customFields) {
      assertCustomFieldsPersisted(afterCreate, config.expectAfterCreate.customFields, "after-create");
    }
    const updateUrl = config.recordPath ? config.recordPath(id) : collectionPath;
    const updateResponse = await apiRequest(request, "PUT", updateUrl, {
      token,
      data: config.update.payload(id)
    });
    expect(
      updateResponse.status(),
      `update ${collectionPath} failed (${updateResponse.status()}): ${await safeText(updateResponse)}`
    ).toBe(config.update.expectedStatus ?? 200);
    const afterUpdate = await read(id);
    expect(afterUpdate, `updated record ${id} should be readable from ${collectionPath}`).toBeTruthy();
    if (config.expectAfterUpdate.scalars) {
      assertScalarFieldsPersisted(afterUpdate, config.expectAfterUpdate.scalars, "after-update");
    }
    if (config.expectAfterUpdate.customFields) {
      assertCustomFieldsPersisted(afterUpdate, config.expectAfterUpdate.customFields, "after-update");
    }
  } finally {
    if (id && config.cleanup !== false) {
      const separator = collectionPath.includes("?") ? "&" : "?";
      const deleteUrl = config.recordPath ? config.recordPath(id) : `${collectionPath}${separator}id=${encodeURIComponent(id)}`;
      await apiRequest(request, "DELETE", deleteUrl, {
        token
      }).catch(() => void 0);
    }
  }
}
export {
  CRUDFORM_EXTENSION_TESTS_DISABLED_ENV,
  assertCustomFieldsPersisted,
  assertScalarFieldsPersisted,
  crudFormExtensionTestsDisabled,
  getCustomFieldValue,
  runCrudFormRoundTrip,
  skipIfCrudFormExtensionTestsDisabled
};
//# sourceMappingURL=crudFormPersistence.js.map
