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 { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
import { serializeOperationMetadata } from "@open-mercato/shared/lib/commands/operationMetadata";
import { tagAssignmentSchema } from "../../../data/validators.js";
import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import { withScopedPayload } from "../../utils.js";
import {
  runCrudMutationGuardAfterSuccess,
  validateCrudMutationGuard
} from "@open-mercato/shared/lib/crud/mutation-guard";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
const TAG_ASSIGNMENT_RESOURCE_KIND = "customers.tagAssignment";
const metadata = {
  POST: { requireAuth: true, requireFeatures: ["customers.activities.manage"] }
};
async function buildContext(req) {
  const container = await createRequestContainer();
  const auth = await getAuthFromRequest(req);
  const { translate } = await resolveTranslations();
  if (!auth) throw new CrudHttpError(401, { error: translate("customers.errors.unauthorized", "Unauthorized") });
  const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
  const ctx = {
    container,
    auth,
    organizationScope: scope,
    selectedOrganizationId: scope?.selectedId ?? auth.orgId ?? null,
    organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),
    request: req
  };
  return { ctx, auth, translate };
}
async function POST(req) {
  try {
    const { ctx, auth, translate } = await buildContext(req);
    const tenantId = auth.tenantId;
    const organizationId = ctx.selectedOrganizationId;
    if (!tenantId || !organizationId) {
      return NextResponse.json({ error: translate("customers.errors.context_required", "Organization and tenant context required") }, { status: 400 });
    }
    const body = await req.json().catch(() => ({}));
    const scoped = withScopedPayload(body, ctx, translate);
    const input = tagAssignmentSchema.parse(scoped);
    const guardResult = await validateCrudMutationGuard(ctx.container, {
      tenantId,
      organizationId,
      userId: auth.sub,
      resourceKind: TAG_ASSIGNMENT_RESOURCE_KIND,
      resourceId: input.entityId,
      operation: "custom",
      requestMethod: req.method,
      requestHeaders: req.headers,
      mutationPayload: input
    });
    if (guardResult && !guardResult.ok) {
      return NextResponse.json(guardResult.body, { status: guardResult.status });
    }
    const commandBus = ctx.container.resolve("commandBus");
    const { result, logEntry } = await commandBus.execute(
      "customers.tags.unassign",
      { input, ctx }
    );
    if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {
      await runCrudMutationGuardAfterSuccess(ctx.container, {
        tenantId,
        organizationId,
        userId: auth.sub,
        resourceKind: TAG_ASSIGNMENT_RESOURCE_KIND,
        resourceId: input.entityId,
        operation: "custom",
        requestMethod: req.method,
        requestHeaders: req.headers,
        metadata: guardResult.metadata ?? null
      });
    }
    const response = NextResponse.json({ id: result?.assignmentId ?? null });
    if (logEntry?.undoToken && logEntry?.id && logEntry?.commandId) {
      response.headers.set(
        "x-om-operation",
        serializeOperationMetadata({
          id: logEntry.id,
          undoToken: logEntry.undoToken,
          commandId: logEntry.commandId,
          actionLabel: logEntry.actionLabel ?? null,
          resourceKind: logEntry.resourceKind ?? "customers.tagAssignment",
          resourceId: logEntry.resourceId ?? result?.assignmentId ?? null,
          executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : void 0
        })
      );
    }
    return response;
  } catch (err) {
    if (isCrudHttpError(err)) {
      return NextResponse.json(err.body, { status: err.status });
    }
    const { translate } = await resolveTranslations();
    logger.error("customers.tags.unassign failed", { err });
    return NextResponse.json({ error: translate("customers.errors.unassign_failed", "Failed to unassign tag") }, { status: 400 });
  }
}
const tagUnassignResponseSchema = z.object({
  id: z.string().uuid().nullable()
});
const tagUnassignErrorSchema = z.object({
  error: z.string()
});
const openApi = {
  tag: "Customers",
  summary: "Unassign customer tag",
  methods: {
    POST: {
      summary: "Remove tag from customer entity",
      description: "Detaches a tag from a customer entity within the validated tenant / organization scope.",
      requestBody: {
        contentType: "application/json",
        schema: tagAssignmentSchema
      },
      responses: [
        { status: 200, description: "Tag unassigned from customer", schema: tagUnassignResponseSchema }
      ],
      errors: [
        { status: 400, description: "Validation or unassignment failed", schema: tagUnassignErrorSchema },
        { status: 401, description: "Unauthorized", schema: tagUnassignErrorSchema },
        { status: 403, description: "Insufficient tenant/organization access", schema: tagUnassignErrorSchema }
      ]
    }
  }
};
export {
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
