import { NextResponse } from "next/server";
import { z } from "zod";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { normalizeExportFormat, serializeExport, defaultExportFilename, ensureColumns } from "@open-mercato/shared/lib/crud/exporters";
import { resolveOrganizationScope, getSelectedOrganizationFromRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
import { SYSTEM_ENTITY_RECORDS_BLOCKED_CODE, isOrmBackedSystemEntityId } from "@open-mercato/shared/lib/data/engine";
import { parseBooleanToken, parseBooleanWithDefault } from "@open-mercato/shared/lib/boolean";
import { enforceCommandOptimisticLockWithGuards } from "@open-mercato/shared/lib/crud/optimistic-lock-command";
import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import { getModules } from "@open-mercato/shared/lib/i18n/server";
import { assertEntityAclForRequest } from "../lib/entityAcl.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("entities").child({ component: "records" });
let declaredCustomEntityIds = null;
function isDeclaredCustomEntity(entityId) {
  if (declaredCustomEntityIds === null) {
    try {
      const mods = getModules();
      if (Array.isArray(mods) && mods.length) {
        const ids = /* @__PURE__ */ new Set();
        for (const mod of mods) {
          for (const spec of mod?.customEntities ?? []) {
            if (spec?.id) ids.add(spec.id);
          }
        }
        declaredCustomEntityIds = ids;
      }
    } catch {
    }
  }
  return declaredCustomEntityIds?.has(entityId) ?? false;
}
const CUSTOM_ENTITY_RECORD_RESOURCE_KIND = "entities.record";
async function classifyRecordsEntity(em, entityId) {
  if (isOrmBackedSystemEntityId(em, entityId)) return "system";
  if (isDeclaredCustomEntity(entityId)) return "custom";
  try {
    const { CustomEntity } = await import("../data/entities.js");
    const found = await em.findOne(CustomEntity, { entityId });
    if (found) return "custom";
  } catch {
  }
  return "unknown";
}
function systemEntityRecordsRejection(entityId) {
  return NextResponse.json(
    { error: "Records are available for custom entities only", code: SYSTEM_ENTITY_RECORDS_BLOCKED_CODE, entityId },
    { status: 400 }
  );
}
async function readCustomEntityRecordUpdatedAt(em, input) {
  try {
    const db = em.getKysely();
    let query = db.selectFrom("custom_entities_storage").select(["updated_at"]).where("entity_type", "=", input.entityType).where("entity_id", "=", input.entityId);
    query = input.organizationId === null ? query.where("organization_id", "is", null) : query.where("organization_id", "=", input.organizationId);
    const row = await query.executeTakeFirst();
    const value = row?.updated_at;
    if (value instanceof Date) return value.toISOString();
    if (typeof value === "string" && value.length > 0) return value;
    return null;
  } catch {
    return null;
  }
}
const metadata = {
  GET: { requireAuth: true, requireFeatures: ["entities.records.view"] },
  POST: { requireAuth: true, requireFeatures: ["entities.records.manage"] },
  PUT: { requireAuth: true, requireFeatures: ["entities.records.manage"] },
  DELETE: { requireAuth: true, requireFeatures: ["entities.records.manage"] }
};
const DEFAULT_EXPORT_PAGE_SIZE = 1e3;
const listRecordsQuerySchema = z.object({
  entityId: z.string().min(1),
  page: z.coerce.number().int().min(1).optional(),
  pageSize: z.coerce.number().int().min(1).max(100).optional(),
  sortField: z.string().optional(),
  sortDir: z.enum(["asc", "desc"]).optional(),
  search: z.string().optional(),
  searchFields: z.string().optional(),
  withDeleted: z.coerce.boolean().optional(),
  format: z.enum(["csv", "json", "xml", "markdown"]).optional(),
  exportScope: z.enum(["full"]).optional(),
  export_scope: z.enum(["full"]).optional(),
  all: z.coerce.boolean().optional(),
  full: z.coerce.boolean().optional()
}).passthrough();
const recordItemSchema = z.record(z.string(), z.any());
const listRecordsResponseSchema = z.object({
  items: z.array(recordItemSchema),
  total: z.number(),
  page: z.number(),
  pageSize: z.number(),
  totalPages: z.number()
});
async function GET(req) {
  const url = new URL(req.url);
  const entityId = url.searchParams.get("entityId") || "";
  if (!entityId) return NextResponse.json({ error: "entityId is required" }, { status: 400 });
  const auth = await getAuthFromRequest(req);
  if (!auth || !auth.tenantId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const requestedExport = normalizeExportFormat(url.searchParams.get("format"));
  const exportScopeRaw = (url.searchParams.get("exportScope") || url.searchParams.get("export_scope") || "").toLowerCase();
  const exportFullRequested = requestedExport != null && (exportScopeRaw === "full" || parseBooleanWithDefault(url.searchParams.get("full"), false));
  const exportAll = parseBooleanWithDefault(url.searchParams.get("all"), false);
  const noPagination = exportAll || requestedExport != null;
  const page = noPagination ? 1 : Math.max(parseInt(url.searchParams.get("page") || "1", 10) || 1, 1);
  const basePageSize = Math.min(Math.max(parseInt(url.searchParams.get("pageSize") || "50", 10) || 50, 1), 100);
  const pageSize = noPagination ? Math.max(basePageSize, DEFAULT_EXPORT_PAGE_SIZE) : basePageSize;
  const sortField = url.searchParams.get("sortField") || "id";
  const sortDir = (url.searchParams.get("sortDir") || "asc").toLowerCase() === "desc" ? "desc" : "asc";
  const withDeleted = parseBooleanWithDefault(url.searchParams.get("withDeleted"), false);
  const searchTerm = (url.searchParams.get("search") || "").trim();
  const searchFields = (url.searchParams.get("searchFields") || "").split(",").map((field) => field.trim()).filter(Boolean);
  const qpEntries = [];
  for (const [key, val] of url.searchParams.entries()) {
    if (["entityId", "page", "pageSize", "sortField", "sortDir", "withDeleted", "format", "exportScope", "export_scope", "all", "full", "search", "searchFields"].includes(key)) continue;
    qpEntries.push([key, val]);
  }
  try {
    const { resolve } = await createRequestContainer();
    const qe = resolve("queryEngine");
    const em = resolve("em");
    const rbac = resolve("rbacService");
    const scope = await resolveOrganizationScope({ em, rbac, auth, selectedId: getSelectedOrganizationFromRequest(req) });
    let organizationIds = scope.filterIds;
    const entityKind = await classifyRecordsEntity(em, entityId);
    if (entityKind === "system") return systemEntityRecordsRejection(entityId);
    const isCustomEntity = entityKind === "custom";
    await assertEntityAclForRequest({ auth, entityId, action: "view", isCustomEntity, rbac });
    if (organizationIds && organizationIds.length === 0) {
      return NextResponse.json({ items: [], total: 0, page, pageSize, totalPages: 0 });
    }
    const normalizeCustomEntityValue = (value) => {
      if (Array.isArray(value)) {
        return value.map((entry) => {
          if (typeof entry !== "string") return entry;
          const parsed2 = parseBooleanToken(entry);
          return parsed2 === null ? entry : parsed2;
        });
      }
      if (typeof value !== "string") return value;
      const parsed = parseBooleanToken(value);
      return parsed === null ? value : parsed;
    };
    const mapRow = (row) => {
      if (!isCustomEntity || !row || typeof row !== "object") return row;
      const out = {};
      for (const [k, v] of Object.entries(row)) {
        if (k.startsWith("cf_")) out[k.replace(/^cf_/, "")] = normalizeCustomEntityValue(v);
        else out[k] = v;
      }
      return out;
    };
    const mapFullRow = (row) => {
      if (!row || typeof row !== "object") return row;
      return { ...row };
    };
    const filtersObj = {};
    const buildFilter = (key, val, allowAnyKey) => {
      if (key.startsWith("cf_")) {
        if (key.endsWith("In")) {
          const base = key.slice(0, -2);
          const values = val.split(",").map((s) => s.trim()).filter(Boolean);
          filtersObj[base] = { $in: values };
        } else {
          if (val.includes(",")) {
            const values = val.split(",").map((s) => s.trim()).filter(Boolean);
            filtersObj[key] = { $in: values };
          } else {
            const parsed = parseBooleanToken(val);
            filtersObj[key] = parsed === null ? val : parsed;
          }
        }
      } else if (allowAnyKey) {
        if (val.includes(",")) {
          const values = val.split(",").map((s) => s.trim()).filter(Boolean);
          filtersObj[key] = { $in: values };
        } else {
          const parsed = parseBooleanToken(val);
          filtersObj[key] = parsed === null ? val : parsed;
        }
      } else {
        if (["id", "created_at", "updated_at", "deleted_at", "name", "title", "email"].includes(key)) {
          ;
          filtersObj[key] = val;
        }
      }
    };
    if (organizationIds && organizationIds.length) {
      filtersObj.organization_id = { $in: organizationIds };
    }
    const qopts = {
      tenantId: auth.tenantId,
      includeCustomFields: true,
      page: { page, pageSize },
      sort: [{ field: sortField, dir: sortDir }],
      filters: filtersObj,
      withDeleted
    };
    if (organizationIds && organizationIds.length) {
      qopts.organizationIds = organizationIds;
    }
    if (isCustomEntity) qopts.forceCustomEntityStorage = true;
    for (const [k, v] of qpEntries) buildFilter(k, v, isCustomEntity);
    if (searchTerm) {
      const fields = searchFields.length ? searchFields : ["id"];
      const pattern = `%${searchTerm}%`;
      const orClauses = fields.map((field) => ({ [field]: { $ilike: pattern } }));
      filtersObj.$or = orClauses;
    }
    const res = await qe.query(entityId, qopts);
    const rawItems = res.items || [];
    const viewPageItems = rawItems.map(mapRow);
    const fullPageItems = rawItems.map(mapFullRow);
    if (isCustomEntity && viewPageItems.length) {
      try {
        const recordIds = viewPageItems.map((it) => it?.id).filter((v) => typeof v === "string" && v.length > 0);
        if (recordIds.length) {
          const db = em.getKysely();
          const rows = await db.selectFrom("custom_entities_storage").select(["entity_id", "updated_at"]).where("entity_type", "=", entityId).where("entity_id", "in", recordIds).execute();
          const updatedById = /* @__PURE__ */ new Map();
          for (const row of rows) {
            const value = row?.updated_at;
            const iso = value instanceof Date ? value.toISOString() : typeof value === "string" && value.length > 0 ? value : null;
            if (iso && row?.entity_id) updatedById.set(String(row.entity_id), iso);
          }
          for (const item of viewPageItems) {
            const iso = updatedById.get(String(item?.id));
            if (iso) {
              item.updated_at = iso;
              item.updatedAt = iso;
            }
          }
        }
      } catch {
      }
    }
    const total = typeof res.total === "number" ? res.total : rawItems.length;
    const effectivePageSize = res.pageSize || pageSize;
    const payload = {
      items: viewPageItems,
      total,
      page: res.page || page,
      pageSize: effectivePageSize,
      totalPages: Math.ceil(total / (effectivePageSize || 1))
    };
    if (requestedExport) {
      let exportItems = exportFullRequested ? [...fullPageItems] : [...viewPageItems];
      if (total > exportItems.length) {
        let nextPage = 2;
        while (exportItems.length < total) {
          const nextRes = await qe.query(entityId, {
            ...qopts,
            page: { page: nextPage, pageSize }
          });
          const nextRawItems = nextRes.items || [];
          if (!nextRawItems.length) break;
          const nextViewItems = nextRawItems.map(mapRow);
          const nextFullItems = nextRawItems.map(mapFullRow);
          const nextBatch = exportFullRequested ? nextFullItems : nextViewItems;
          exportItems.push(...nextBatch);
          if (nextBatch.length < pageSize) break;
          nextPage += 1;
        }
      }
      const prepared = {
        columns: ensureColumns(exportItems),
        rows: exportItems
      };
      const filenameBase = exportFullRequested ? `${entityId || "records"}_full` : entityId || "records";
      const serialized = serializeExport(prepared, requestedExport);
      const filename = defaultExportFilename(filenameBase, requestedExport);
      return new Response(serialized.body, {
        headers: {
          "content-type": serialized.contentType,
          "content-disposition": `attachment; filename="${filename}"`
        }
      });
    }
    return NextResponse.json(payload);
  } catch (e) {
    if (isCrudHttpError(e)) return NextResponse.json(e.body, { status: e.status });
    logger.error("Records GET failed", { err: e });
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
const postBodySchema = z.object({
  entityId: z.string().min(1),
  recordId: z.string().min(1).optional(),
  values: z.record(z.string(), z.any()).default({})
});
const putBodySchema = z.object({
  entityId: z.string().min(1),
  recordId: z.string().min(1),
  values: z.record(z.string(), z.any()).default({})
});
const mutationResponseSchema = z.object({
  ok: z.literal(true),
  item: z.object({
    entityId: z.string(),
    recordId: z.string()
  }).optional()
});
async function POST(req) {
  const auth = await getAuthFromRequest(req);
  if (!auth || !auth.tenantId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  let json;
  try {
    json = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
  }
  const parsed = postBodySchema.safeParse(json);
  if (!parsed.success) return NextResponse.json({ error: "Validation failed", details: parsed.error.flatten() }, { status: 400 });
  const { entityId } = parsed.data;
  let { recordId, values } = parsed.data;
  try {
    const { resolve } = await createRequestContainer();
    const de = resolve("dataEngine");
    const em = resolve("em");
    const rbac = resolve("rbacService");
    const scope = await resolveOrganizationScope({ em, rbac, auth, selectedId: getSelectedOrganizationFromRequest(req) });
    const targetOrgId = scope.selectedId ?? auth.orgId;
    if (!targetOrgId) return NextResponse.json({ error: "Organization context is required" }, { status: 400 });
    const entityKind = await classifyRecordsEntity(em, entityId);
    if (entityKind === "system") return systemEntityRecordsRejection(entityId);
    const isCustomEntity = entityKind === "custom";
    await assertEntityAclForRequest({ auth, entityId, action: "manage", isCustomEntity, rbac });
    for (const reservedKey of ["id", "created_at", "createdAt", "updated_at", "updatedAt", "deleted_at", "deletedAt"]) {
      delete values[reservedKey];
    }
    const norm = normalizeValues(values);
    try {
      const { validateCustomFieldValuesServer } = await import("../lib/validation.js");
      const check = await validateCustomFieldValuesServer(em, { entityId, organizationId: targetOrgId, tenantId: auth.tenantId, values: norm, rejectUndeclaredKeys: true });
      if (!check.ok) return NextResponse.json({ error: "Validation failed", fields: check.fieldErrors }, { status: 400 });
    } catch {
    }
    const normalizedRecordId = (() => {
      const raw = String(recordId || "").trim();
      if (!raw) return void 0;
      const low = raw.toLowerCase();
      if (low === "create" || low === "new" || low === "null" || low === "undefined") return void 0;
      const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
      return uuid.test(raw) ? raw : void 0;
    })();
    const { id } = await de.createCustomEntityRecord({
      entityId,
      recordId: normalizedRecordId,
      organizationId: targetOrgId,
      tenantId: auth.tenantId,
      values: norm
    });
    return NextResponse.json({ ok: true, item: { entityId, recordId: id } });
  } catch (e) {
    if (isCrudHttpError(e)) return NextResponse.json(e.body, { status: e.status });
    logger.error("Records POST failed", { err: e });
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
function parsePutBody(json) {
  if (!json || typeof json !== "object") return { ok: false, error: "Invalid JSON" };
  const entityId = typeof json.entityId === "string" && json.entityId.length ? json.entityId : "";
  const recordId = typeof json.recordId === "string" && json.recordId.length ? json.recordId : "";
  const values = json.values && typeof json.values === "object" ? json.values : {};
  if (!entityId || !recordId) return { ok: false, error: "entityId and recordId are required" };
  return { ok: true, data: { entityId, recordId, values } };
}
async function PUT(req) {
  const auth = await getAuthFromRequest(req);
  if (!auth || !auth.tenantId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  let json;
  try {
    json = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
  }
  const parsed = parsePutBody(json);
  if (!parsed.ok) return NextResponse.json({ error: parsed.error }, { status: 400 });
  const { entityId, recordId, values } = parsed.data;
  try {
    const container = await createRequestContainer();
    const { resolve } = container;
    const de = resolve("dataEngine");
    const em = resolve("em");
    const rbac = resolve("rbacService");
    const scope = await resolveOrganizationScope({ em, rbac, auth, selectedId: getSelectedOrganizationFromRequest(req) });
    const targetOrgId = scope.selectedId ?? auth.orgId;
    if (!targetOrgId) return NextResponse.json({ error: "Organization context is required" }, { status: 400 });
    const entityKind = await classifyRecordsEntity(em, entityId);
    if (entityKind === "system") return systemEntityRecordsRejection(entityId);
    const isCustomEntity = entityKind === "custom";
    await assertEntityAclForRequest({ auth, entityId, action: "manage", isCustomEntity, rbac });
    for (const reservedKey of ["id", "created_at", "createdAt", "updated_at", "updatedAt", "deleted_at", "deletedAt"]) {
      delete values[reservedKey];
    }
    const norm = normalizeValues(values);
    try {
      const { validateCustomFieldValuesServer } = await import("../lib/validation.js");
      const check = await validateCustomFieldValuesServer(em, { entityId, organizationId: targetOrgId, tenantId: auth.tenantId, values: norm, rejectUndeclaredKeys: true });
      if (!check.ok) return NextResponse.json({ error: "Validation failed", fields: check.fieldErrors }, { status: 400 });
    } catch {
    }
    const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
    const rid = String(recordId || "").trim();
    const low = rid.toLowerCase();
    const isSentinel = !rid || low === "create" || low === "new" || low === "null" || low === "undefined";
    const isUuid = uuidRe.test(rid);
    if (isSentinel || !isUuid) {
      const created = await de.createCustomEntityRecord({
        entityId,
        recordId: void 0,
        organizationId: targetOrgId,
        tenantId: auth.tenantId,
        values: norm
      });
      return NextResponse.json({ ok: true, item: { entityId, recordId: created.id } });
    }
    try {
      const currentUpdatedAt = await readCustomEntityRecordUpdatedAt(em, {
        entityType: entityId,
        entityId: rid,
        organizationId: targetOrgId
      });
      await enforceCommandOptimisticLockWithGuards(container, {
        resourceKind: CUSTOM_ENTITY_RECORD_RESOURCE_KIND,
        resourceId: rid,
        current: currentUpdatedAt,
        request: req
      });
    } catch (lockError) {
      if (isCrudHttpError(lockError)) {
        return NextResponse.json(lockError.body, { status: lockError.status });
      }
      throw lockError;
    }
    await de.updateCustomEntityRecord({
      entityId,
      recordId: rid,
      organizationId: targetOrgId,
      tenantId: auth.tenantId,
      values: norm
    });
    return NextResponse.json({ ok: true, item: { entityId, recordId: rid } });
  } catch (e) {
    if (isCrudHttpError(e)) return NextResponse.json(e.body, { status: e.status });
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
const deleteBodySchema = z.object({
  entityId: z.string().min(1),
  recordId: z.string().min(1)
});
async function DELETE(req) {
  const auth = await getAuthFromRequest(req);
  if (!auth || !auth.tenantId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const url = new URL(req.url);
  const qpEntityId = url.searchParams.get("entityId");
  const qpRecordId = url.searchParams.get("recordId");
  let payload = qpEntityId && qpRecordId ? { entityId: qpEntityId, recordId: qpRecordId } : null;
  if (!payload) {
    try {
      payload = await req.json();
    } catch {
      payload = null;
    }
  }
  const parsed = deleteBodySchema.safeParse(payload);
  if (!parsed.success) return NextResponse.json({ error: "Validation failed", details: parsed.error.flatten() }, { status: 400 });
  const { entityId, recordId } = parsed.data;
  try {
    const container = await createRequestContainer();
    const { resolve } = container;
    const de = resolve("dataEngine");
    const em = resolve("em");
    const rbac = resolve("rbacService");
    const scope = await resolveOrganizationScope({ em, rbac, auth, selectedId: getSelectedOrganizationFromRequest(req) });
    const targetOrgId = scope.selectedId ?? auth.orgId;
    if (!targetOrgId) return NextResponse.json({ error: "Organization context is required" }, { status: 400 });
    const entityKind = await classifyRecordsEntity(em, entityId);
    if (entityKind === "system") return systemEntityRecordsRejection(entityId);
    const isCustomEntity = entityKind === "custom";
    await assertEntityAclForRequest({ auth, entityId, action: "manage", isCustomEntity, rbac });
    try {
      const currentUpdatedAt = await readCustomEntityRecordUpdatedAt(em, {
        entityType: entityId,
        entityId: recordId,
        organizationId: targetOrgId
      });
      await enforceCommandOptimisticLockWithGuards(container, {
        resourceKind: CUSTOM_ENTITY_RECORD_RESOURCE_KIND,
        resourceId: recordId,
        current: currentUpdatedAt,
        request: req
      });
    } catch (lockError) {
      if (isCrudHttpError(lockError)) {
        return NextResponse.json(lockError.body, { status: lockError.status });
      }
      throw lockError;
    }
    await de.deleteCustomEntityRecord({ entityId, recordId, organizationId: targetOrgId, tenantId: auth.tenantId, soft: true });
    return NextResponse.json({ ok: true });
  } catch (e) {
    if (isCrudHttpError(e)) return NextResponse.json(e.body, { status: e.status });
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
function normalizeValues(input) {
  const out = {};
  for (const [k, v] of Object.entries(input || {})) {
    const key = k.startsWith("cf_") ? k.replace(/^cf_/, "") : k;
    out[key] = v;
  }
  return out;
}
const deleteResponseSchema = z.object({
  ok: z.literal(true)
});
const errorSchema = z.object({
  error: z.string()
}).passthrough();
const openApi = {
  tag: "Entities",
  summary: "CRUD operations on entity records",
  methods: {
    GET: {
      summary: "List records",
      description: "Returns paginated records for the supplied entity. Supports custom field filters, exports, and soft-delete toggles.",
      query: listRecordsQuerySchema,
      responses: [
        {
          status: 200,
          description: "Paginated records",
          schema: listRecordsResponseSchema
        },
        {
          status: 400,
          description: "Missing entity id",
          schema: errorSchema
        },
        {
          status: 401,
          description: "Missing authentication",
          schema: errorSchema
        },
        {
          status: 500,
          description: "Unexpected failure",
          schema: errorSchema
        }
      ]
    },
    POST: {
      summary: "Create record",
      description: "Creates a record for the given entity. When `recordId` is omitted or not a UUID the data engine will generate one automatically.",
      requestBody: {
        contentType: "application/json",
        schema: postBodySchema
      },
      responses: [
        {
          status: 200,
          description: "Record created",
          schema: mutationResponseSchema
        },
        {
          status: 400,
          description: "Validation failure",
          schema: errorSchema
        },
        {
          status: 401,
          description: "Missing authentication",
          schema: errorSchema
        },
        {
          status: 500,
          description: "Unexpected failure",
          schema: errorSchema
        }
      ]
    },
    PUT: {
      summary: "Update record",
      description: "Updates an existing record. If the provided recordId is not a UUID the record will be created instead to support optimistic flows.",
      requestBody: {
        contentType: "application/json",
        schema: putBodySchema
      },
      responses: [
        {
          status: 200,
          description: "Record updated",
          schema: mutationResponseSchema
        },
        {
          status: 400,
          description: "Validation failure",
          schema: errorSchema
        },
        {
          status: 401,
          description: "Missing authentication",
          schema: errorSchema
        },
        {
          status: 500,
          description: "Unexpected failure",
          schema: errorSchema
        }
      ]
    },
    DELETE: {
      summary: "Delete record",
      description: "Soft deletes the specified record within the current tenant/org scope.",
      requestBody: {
        contentType: "application/json",
        schema: deleteBodySchema
      },
      responses: [
        {
          status: 200,
          description: "Record deleted",
          schema: deleteResponseSchema
        },
        {
          status: 400,
          description: "Missing entity id or record id",
          schema: errorSchema
        },
        {
          status: 401,
          description: "Missing authentication",
          schema: errorSchema
        },
        {
          status: 404,
          description: "Record not found",
          schema: errorSchema
        },
        {
          status: 500,
          description: "Unexpected failure",
          schema: errorSchema
        }
      ]
    }
  }
};
export {
  DELETE,
  GET,
  POST,
  PUT,
  metadata,
  openApi
};
//# sourceMappingURL=records.js.map
