import { NextResponse } from "next/server";
import { z } from "zod";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { SyncMapping } from "@open-mercato/core/modules/data_sync/data/entities";
import {
  runCrudMutationGuardAfterSuccess,
  validateCrudMutationGuard
} from "@open-mercato/shared/lib/crud/mutation-guard";
const idParamsSchema = z.object({ id: z.string().uuid() });
const updateMappingSchema = z.object({
  mapping: z.record(z.string(), z.unknown())
});
const metadata = {
  GET: { requireAuth: true, requireFeatures: ["data_sync.configure"] },
  PUT: { requireAuth: true, requireFeatures: ["data_sync.configure"] },
  DELETE: { requireAuth: true, requireFeatures: ["data_sync.configure"] }
};
const openApi = {
  tags: ["DataSync"],
  summary: "Get, update, or delete a field mapping"
};
async function resolveParams(ctx) {
  const rawParams = ctx.params && typeof ctx.params.then === "function" ? await ctx.params : ctx.params;
  return idParamsSchema.safeParse(rawParams);
}
async function GET(req, ctx) {
  const auth = await getAuthFromRequest(req);
  if (!auth?.tenantId || !auth.orgId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const parsedParams = await resolveParams(ctx);
  if (!parsedParams.success) {
    return NextResponse.json({ error: "Invalid mapping id" }, { status: 400 });
  }
  const container = await createRequestContainer();
  const em = container.resolve("em");
  const scope = { organizationId: auth.orgId, tenantId: auth.tenantId };
  const mapping = await findOneWithDecryption(
    em,
    SyncMapping,
    {
      id: parsedParams.data.id,
      organizationId: auth.orgId,
      tenantId: auth.tenantId
    },
    void 0,
    scope
  );
  if (!mapping) {
    return NextResponse.json({ error: "Mapping not found" }, { status: 404 });
  }
  return NextResponse.json({
    id: mapping.id,
    integrationId: mapping.integrationId,
    entityType: mapping.entityType,
    mapping: mapping.mapping,
    createdAt: mapping.createdAt.toISOString(),
    updatedAt: mapping.updatedAt.toISOString()
  });
}
async function PUT(req, ctx) {
  const auth = await getAuthFromRequest(req);
  if (!auth?.tenantId || !auth.orgId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const parsedParams = await resolveParams(ctx);
  if (!parsedParams.success) {
    return NextResponse.json({ error: "Invalid mapping id" }, { status: 400 });
  }
  const payload = await req.json().catch(() => null);
  const parsedBody = updateMappingSchema.safeParse(payload);
  if (!parsedBody.success) {
    return NextResponse.json({ error: "Invalid payload", details: parsedBody.error.flatten() }, { status: 422 });
  }
  const container = await createRequestContainer();
  const em = container.resolve("em");
  const scope = { organizationId: auth.orgId, tenantId: auth.tenantId };
  const mapping = await findOneWithDecryption(
    em,
    SyncMapping,
    {
      id: parsedParams.data.id,
      organizationId: auth.orgId,
      tenantId: auth.tenantId
    },
    void 0,
    scope
  );
  if (!mapping) {
    return NextResponse.json({ error: "Mapping not found" }, { status: 404 });
  }
  const guardResult = await validateCrudMutationGuard(container, {
    tenantId: scope.tenantId,
    organizationId: scope.organizationId,
    userId: auth.sub,
    resourceKind: "data_sync.mapping",
    resourceId: mapping.id,
    operation: "update",
    requestMethod: req.method,
    requestHeaders: req.headers,
    mutationPayload: parsedBody.data
  });
  if (guardResult && !guardResult.ok) {
    return NextResponse.json(guardResult.body, { status: guardResult.status });
  }
  mapping.mapping = parsedBody.data.mapping;
  await em.flush();
  if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {
    await runCrudMutationGuardAfterSuccess(container, {
      tenantId: scope.tenantId,
      organizationId: scope.organizationId,
      userId: auth.sub,
      resourceKind: "data_sync.mapping",
      resourceId: mapping.id,
      operation: "update",
      requestMethod: req.method,
      requestHeaders: req.headers,
      metadata: guardResult.metadata ?? null
    });
  }
  return NextResponse.json({
    id: mapping.id,
    integrationId: mapping.integrationId,
    entityType: mapping.entityType,
    mapping: mapping.mapping,
    updatedAt: mapping.updatedAt.toISOString()
  });
}
async function DELETE(req, ctx) {
  const auth = await getAuthFromRequest(req);
  if (!auth?.tenantId || !auth.orgId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const parsedParams = await resolveParams(ctx);
  if (!parsedParams.success) {
    return NextResponse.json({ error: "Invalid mapping id" }, { status: 400 });
  }
  const container = await createRequestContainer();
  const em = container.resolve("em");
  const scope = { organizationId: auth.orgId, tenantId: auth.tenantId };
  const mapping = await findOneWithDecryption(
    em,
    SyncMapping,
    {
      id: parsedParams.data.id,
      organizationId: auth.orgId,
      tenantId: auth.tenantId
    },
    void 0,
    scope
  );
  if (!mapping) {
    return NextResponse.json({ error: "Mapping not found" }, { status: 404 });
  }
  const guardResult = await validateCrudMutationGuard(container, {
    tenantId: scope.tenantId,
    organizationId: scope.organizationId,
    userId: auth.sub,
    resourceKind: "data_sync.mapping",
    resourceId: mapping.id,
    operation: "delete",
    requestMethod: req.method,
    requestHeaders: req.headers,
    mutationPayload: null
  });
  if (guardResult && !guardResult.ok) {
    return NextResponse.json(guardResult.body, { status: guardResult.status });
  }
  const mappingId = mapping.id;
  em.remove(mapping);
  await em.flush();
  if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {
    await runCrudMutationGuardAfterSuccess(container, {
      tenantId: scope.tenantId,
      organizationId: scope.organizationId,
      userId: auth.sub,
      resourceKind: "data_sync.mapping",
      resourceId: mappingId,
      operation: "delete",
      requestMethod: req.method,
      requestHeaders: req.headers,
      metadata: guardResult.metadata ?? null
    });
  }
  return NextResponse.json({ deleted: true });
}
export {
  DELETE,
  GET,
  PUT,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
