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 { interactionCompleteSchema } from "../../../data/validators.js";
import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
import {
  runCrudMutationGuardAfterSuccess,
  validateCrudMutationGuard
} from "@open-mercato/shared/lib/crud/mutation-guard";
import { resolveAuthActorId } from "../../../lib/interactionRequestContext.js";
import { withOperationMetadata } from "../../../lib/operationMetadata.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
const metadata = {
  POST: { requireAuth: true, requireFeatures: ["customers.interactions.manage"] }
};
async function POST(req) {
  try {
    const container = await createRequestContainer();
    const auth = await getAuthFromRequest(req);
    const { translate } = await resolveTranslations();
    if (!auth || !auth.tenantId) {
      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
    };
    const body = await readJsonSafe(req, {});
    const parsed = interactionCompleteSchema.parse(body);
    const guardUserId = resolveAuthActorId(auth);
    const guardResult = await validateCrudMutationGuard(container, {
      tenantId: auth.tenantId,
      organizationId: ctx.selectedOrganizationId,
      userId: guardUserId,
      resourceKind: "customers.interaction",
      resourceId: parsed.id,
      operation: "custom",
      requestMethod: req.method,
      requestHeaders: req.headers,
      mutationPayload: parsed
    });
    if (guardResult && !guardResult.ok) {
      return NextResponse.json(guardResult.body, { status: guardResult.status });
    }
    const commandBus = ctx.container.resolve("commandBus");
    const { logEntry } = await commandBus.execute(
      "customers.interactions.complete",
      { input: parsed, ctx }
    );
    if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {
      await runCrudMutationGuardAfterSuccess(container, {
        tenantId: auth.tenantId,
        organizationId: ctx.selectedOrganizationId,
        userId: guardUserId,
        resourceKind: "customers.interaction",
        resourceId: parsed.id,
        operation: "custom",
        requestMethod: req.method,
        requestHeaders: req.headers,
        metadata: guardResult.metadata ?? null
      });
    }
    return withOperationMetadata(
      NextResponse.json({ ok: true }),
      logEntry,
      { resourceKind: "customers.interaction", resourceId: parsed.id }
    );
  } catch (err) {
    if (isCrudHttpError(err)) {
      return NextResponse.json(err.body, { status: err.status });
    }
    if (err instanceof z.ZodError) {
      return NextResponse.json({ error: "Validation failed", details: err.issues }, { status: 400 });
    }
    logger.error("customers.interactions.complete failed", { err });
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
const okResponseSchema = z.object({ ok: z.boolean() });
const errorSchema = z.object({ error: z.string() });
const openApi = {
  tag: "Customers",
  summary: "Complete an interaction",
  methods: {
    POST: {
      summary: "Complete an interaction",
      description: "Marks an interaction as done and sets occurredAt to current time (or a provided timestamp).",
      requestBody: { contentType: "application/json", schema: interactionCompleteSchema },
      responses: [
        { status: 200, description: "Interaction completed", schema: okResponseSchema }
      ],
      errors: [
        { status: 400, description: "Validation failed", schema: errorSchema },
        { status: 401, description: "Unauthorized", schema: errorSchema },
        { status: 404, description: "Interaction not found", schema: errorSchema }
      ]
    }
  }
};
export {
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
