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 { CustomFieldDef } from "@open-mercato/core/modules/entities/data/entities";
import { loadEntityFieldsetConfigs } from "../lib/fieldsets.js";
import { resolveDefinitionMutationScope } from "../lib/definition-scope.js";
import { resolveEntityDefinitionsVersion } from "../lib/definitions-version.js";
const metadata = {
  GET: { requireAuth: true, requireFeatures: ["entities.definitions.manage"] }
};
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 || !auth.orgId && !auth.isSuperAdmin) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const container = await createRequestContainer();
  const { resolve } = container;
  const em = resolve("em");
  const versionScope = await resolveDefinitionMutationScope({ auth, container, request: req });
  const [defs, tombstones, configMap] = await Promise.all([
    em.find(CustomFieldDef, {
      entityId,
      deletedAt: null,
      isActive: true,
      $and: [
        { $or: [{ organizationId: auth.orgId ?? void 0 }, { organizationId: null }] },
        { $or: [{ tenantId: auth.tenantId ?? void 0 }, { tenantId: null }] }
      ]
    }, { orderBy: { key: "asc" } }),
    em.find(CustomFieldDef, {
      entityId,
      deletedAt: { $ne: null },
      $and: [
        { $or: [{ organizationId: auth.orgId ?? void 0 }, { organizationId: null }] },
        { $or: [{ tenantId: auth.tenantId ?? void 0 }, { tenantId: null }] }
      ]
    }),
    loadEntityFieldsetConfigs(em, {
      entityIds: [entityId],
      tenantId: auth.tenantId ?? null,
      organizationId: auth.orgId ?? null,
      mode: "manage"
    })
  ]);
  const tombstonedKeys = new Set(tombstones.map((d) => d.key));
  const byKey = /* @__PURE__ */ new Map();
  const ts = (x) => {
    const u = x?.updatedAt instanceof Date ? x.updatedAt.getTime() : x?.updatedAt ? new Date(x.updatedAt).getTime() : 0;
    if (u) return u;
    const c = x?.createdAt instanceof Date ? x.createdAt.getTime() : x?.createdAt ? new Date(x.createdAt).getTime() : 0;
    return c;
  };
  const scopeScore = (x) => (x?.tenantId ? 2 : 0) + (x?.organizationId ? 1 : 0);
  for (const d of defs) {
    const existing = byKey.get(d.key);
    if (!existing) {
      byKey.set(d.key, d);
      continue;
    }
    const sNew = scopeScore(d);
    const sOld = scopeScore(existing);
    if (sNew > sOld) {
      byKey.set(d.key, d);
      continue;
    }
    if (sNew < sOld) continue;
    const tNew = ts(d);
    const tOld = ts(existing);
    if (tNew >= tOld) byKey.set(d.key, d);
  }
  const winners = Array.from(byKey.values()).filter((d) => !tombstonedKeys.has(d.key));
  const items = winners.map((d) => ({
    id: d.id,
    key: d.key,
    kind: d.kind,
    configJson: d.configJson,
    isActive: d.isActive,
    organizationId: d.organizationId ?? null,
    tenantId: d.tenantId ?? null
  }));
  const deletedKeys = Array.from(tombstonedKeys);
  const cfg = configMap.get(entityId) ?? { fieldsets: [], singleFieldsetPerRecord: true };
  const version = await resolveEntityDefinitionsVersion(em, {
    entityId,
    tenantId: versionScope.tenantId,
    organizationId: versionScope.organizationId
  });
  return NextResponse.json({
    items,
    deletedKeys,
    fieldsets: cfg.fieldsets,
    settings: { singleFieldsetPerRecord: cfg.singleFieldsetPerRecord },
    version
  });
}
const definitionsManageQuerySchema = z.object({
  entityId: z.string()
});
const managedDefinitionSchema = z.object({
  id: z.string().uuid(),
  key: z.string(),
  kind: z.string(),
  configJson: z.record(z.string(), z.any()).nullable().optional(),
  isActive: z.boolean().optional(),
  organizationId: z.string().uuid().nullable(),
  tenantId: z.string().uuid().nullable()
});
const manageFieldsetGroupSchema = z.object({
  code: z.string(),
  title: z.string().optional(),
  hint: z.string().optional()
});
const manageFieldsetSchema = z.object({
  code: z.string(),
  label: z.string(),
  icon: z.string().optional(),
  description: z.string().optional(),
  groups: z.array(manageFieldsetGroupSchema).optional()
});
const definitionsManageResponseSchema = z.object({
  items: z.array(managedDefinitionSchema),
  deletedKeys: z.array(z.string()),
  fieldsets: z.array(manageFieldsetSchema).optional(),
  settings: z.object({ singleFieldsetPerRecord: z.boolean().optional() }).optional(),
  version: z.string().nullable().optional()
});
const openApi = {
  tag: "Entities",
  summary: "Inspect scoped custom field definitions",
  methods: {
    GET: {
      summary: "Get management snapshot",
      description: "Returns scoped custom field definitions (including inactive tombstones) for administration interfaces.",
      query: definitionsManageQuerySchema,
      responses: [
        {
          status: 200,
          description: "Scoped definitions and deleted keys",
          schema: definitionsManageResponseSchema
        },
        {
          status: 400,
          description: "Missing entity id",
          schema: z.object({ error: z.string() })
        },
        {
          status: 401,
          description: "Missing authentication or feature",
          schema: z.object({ error: z.string() })
        }
      ]
    }
  }
};
export {
  GET,
  metadata,
  openApi
};
//# sourceMappingURL=definitions.manage.js.map
