import { NextResponse } from "next/server";
import { z } from "zod";
import { resolveTranslationsRouteContext, resolveTranslationsActorId } from "@open-mercato/core/modules/translations/api/context";
import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import {
  runCrudMutationGuardAfterSuccess,
  validateCrudMutationGuard
} from "@open-mercato/shared/lib/crud/mutation-guard";
import { isValidIso639 } from "@open-mercato/shared/lib/i18n/iso639";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("translations").child({ component: "locales" });
const bodySchema = z.object({
  locales: z.array(
    z.string().min(2).max(10).refine(isValidIso639, { message: "Invalid ISO 639-1 language code" })
  ).min(1).max(50)
});
const metadata = {
  path: "/translations/locales",
  PUT: { requireAuth: true, requireFeatures: ["translations.manage_locales"] }
};
async function PUT(req) {
  try {
    const context = await resolveTranslationsRouteContext(req);
    const body = bodySchema.parse(await req.json());
    const uniqueLocales = [...new Set(body.locales.map((l) => l.toLowerCase().trim()))];
    const guardUserId = resolveTranslationsActorId(context.auth);
    const guardResult = await validateCrudMutationGuard(context.container, {
      tenantId: context.tenantId,
      organizationId: context.organizationId,
      userId: guardUserId,
      resourceKind: "translations.locales",
      resourceId: "supported_locales",
      operation: "custom",
      requestMethod: req.method,
      requestHeaders: req.headers,
      mutationPayload: { locales: uniqueLocales }
    });
    if (guardResult && !guardResult.ok) {
      return NextResponse.json(guardResult.body, { status: guardResult.status });
    }
    const configService = context.container.resolve("moduleConfigService");
    await configService.setValue("translations", "supported_locales", uniqueLocales, { tenantId: context.tenantId });
    if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {
      await runCrudMutationGuardAfterSuccess(context.container, {
        tenantId: context.tenantId,
        organizationId: context.organizationId,
        userId: guardUserId,
        resourceKind: "translations.locales",
        resourceId: "supported_locales",
        operation: "custom",
        requestMethod: req.method,
        requestHeaders: req.headers,
        metadata: guardResult.metadata ?? null
      });
    }
    return NextResponse.json({ locales: uniqueLocales });
  } catch (err) {
    if (isCrudHttpError(err)) {
      return NextResponse.json(err.body, { status: err.status });
    }
    if (err instanceof z.ZodError) {
      return NextResponse.json({ error: "Invalid request", details: err.issues }, { status: 400 });
    }
    logger.error("Failed to update locales", { err });
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
const responseSchema = z.object({
  locales: z.array(z.string())
});
const putDoc = {
  summary: "Update supported translation locales",
  tags: ["Translations"],
  requestBody: {
    schema: bodySchema
  },
  responses: [
    { status: 200, description: "Updated locales list", schema: responseSchema }
  ],
  errors: [
    { status: 400, description: "Invalid request body" }
  ]
};
const openApi = {
  tag: "Translations",
  summary: "Update supported translation locales",
  methods: {
    PUT: putDoc
  }
};
var locales_default = PUT;
export {
  locales_default as default,
  metadata,
  openApi
};
//# sourceMappingURL=locales.js.map
