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 { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import { documentNumberRequestSchema } from "../../data/validators.js";
import { withScopedPayload } from "../utils.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("sales");
const metadata = {
  POST: { requireAuth: true }
};
async function resolveRequestContext(req) {
  const container = await createRequestContainer();
  const auth = await getAuthFromRequest(req);
  const { translate } = await resolveTranslations();
  if (!auth || !auth.tenantId) {
    throw new CrudHttpError(401, { error: translate("sales.documents.errors.unauthorized", "Unauthorized") });
  }
  const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
  const organizationId = scope?.selectedId ?? auth.orgId ?? null;
  if (!organizationId) {
    throw new CrudHttpError(400, {
      error: translate("sales.documents.errors.organization_required", "Organization context is required")
    });
  }
  const ctx = {
    container,
    auth,
    organizationScope: scope,
    selectedOrganizationId: organizationId,
    organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),
    request: req
  };
  return { ctx, translate };
}
async function ensureKindPermission(ctx, kind, translate) {
  const rbac = ctx.container.resolve("rbacService");
  const auth = ctx.auth;
  if (!rbac || !auth?.sub) return;
  const kindFeatureMap = {
    order: "sales.orders.manage",
    quote: "sales.quotes.manage",
    invoice: "sales.invoices.manage",
    credit_memo: "sales.credit_memos.manage"
  };
  const requiredFeatures = [
    kindFeatureMap[kind] ?? "sales.orders.manage",
    "sales.documents.number.edit"
  ];
  const ok = await rbac.userHasAllFeatures(auth.sub, requiredFeatures, {
    tenantId: auth.tenantId ?? null,
    organizationId: ctx.selectedOrganizationId ?? auth.orgId ?? null
  });
  if (!ok) {
    throw new CrudHttpError(403, {
      error: translate("sales.documents.errors.number_forbidden", "You cannot generate document numbers.")
    });
  }
}
async function POST(req) {
  try {
    const { ctx, translate } = await resolveRequestContext(req);
    const payload = await req.json().catch(() => ({}));
    const scoped = withScopedPayload(payload, ctx, translate);
    const input = documentNumberRequestSchema.parse(scoped);
    await ensureKindPermission(ctx, input.kind, translate);
    const generator = ctx.container.resolve("salesDocumentNumberGenerator");
    const result = await generator.generate({
      kind: input.kind,
      organizationId: input.organizationId,
      tenantId: input.tenantId,
      format: input.format
    });
    return NextResponse.json({
      number: result.number,
      format: result.format,
      sequence: result.sequence
    });
  } catch (err) {
    if (isCrudHttpError(err)) {
      return NextResponse.json(err.body, { status: err.status });
    }
    const { translate } = await resolveTranslations();
    logger.error("sales.document-numbers.generate failed", { err });
    return NextResponse.json(
      { error: translate("sales.documents.errors.number_generate_failed", "Failed to generate document number.") },
      { status: 400 }
    );
  }
}
const openApi = {
  tag: "Sales",
  summary: "Generate sales document number",
  methods: {
    POST: {
      summary: "Generate next number",
      description: "Generates the next sales order or quote number using configured formatting rules.",
      requestBody: {
        contentType: "application/json",
        schema: documentNumberRequestSchema
      },
      responses: [
        {
          status: 200,
          description: "Generated number",
          schema: z.object({
            number: z.string(),
            format: z.string(),
            sequence: z.number()
          })
        },
        { status: 400, description: "Invalid input or scope missing", schema: z.object({ error: z.string() }) },
        { status: 401, description: "Unauthorized", schema: z.object({ error: z.string() }) }
      ]
    }
  }
};
export {
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
