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 { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import { resolveFeatureCheckContext } from "@open-mercato/core/modules/directory/utils/organizationScope";
import { executeUpgradeAction, getCurrentVersion, isUpgradeActionsEnabled, listPendingUpgradeActions } from "../../services/upgradeActionsService.js";
import {
  configsTag,
  upgradeActionsListResponseSchema,
  executeUpgradeActionRequestSchema,
  executeUpgradeActionResponseSchema,
  configErrorSchema
} from "../openapi.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("configs");
const metadata = {
  GET: { requireAuth: true, requireFeatures: ["configs.manage"] },
  POST: { requireAuth: true, requireFeatures: ["configs.manage"] }
};
const runSchema = z.object({
  actionId: z.string().trim().min(1, "action id required")
});
async function resolveScope(req, translate) {
  const auth = await getAuthFromRequest(req);
  if (!auth?.sub) {
    return { scope: null, container: null, error: NextResponse.json({ error: "Unauthorized" }, { status: 401 }) };
  }
  const container = await createRequestContainer();
  const featureContext = await resolveFeatureCheckContext({ container, auth, request: req });
  const tenantId = featureContext.scope.tenantId ?? auth.tenantId ?? null;
  const organizationId = featureContext.organizationId ?? featureContext.scope.selectedId ?? auth.orgId ?? null;
  if (!tenantId || !organizationId) {
    const message = translate(
      "upgrades.scopeRequired",
      "Select an organization and tenant to apply this upgrade."
    );
    return { scope: null, container, error: NextResponse.json({ error: message }, { status: 400 }) };
  }
  return {
    scope: { tenantId, organizationId },
    container
  };
}
async function GET(req) {
  if (!isUpgradeActionsEnabled()) {
    return NextResponse.json({ version: getCurrentVersion(), actions: [] });
  }
  const { translate } = await resolveTranslations();
  const scopedTranslate = (key, fallback, params) => translate(key, fallback, params);
  const scopeResult = await resolveScope(req, scopedTranslate);
  if (!scopeResult.scope) return scopeResult.error;
  const container = scopeResult.container ?? await createRequestContainer();
  const em = container.resolve("em");
  const version = getCurrentVersion();
  try {
    const actions = await listPendingUpgradeActions(em, { ...scopeResult.scope, version });
    const nextAction = actions[0];
    const payload = nextAction ? [{
      id: nextAction.id,
      version: nextAction.version,
      message: translate(
        nextAction.messageKey,
        'The version {{version}} has been installed. To fully use all the features from this edition please do "Install example catalog products and categories".',
        { version: nextAction.version }
      ),
      ctaLabel: translate(
        nextAction.ctaKey,
        "Install example catalog products and categories"
      ),
      successMessage: translate(
        nextAction.successKey,
        "Example catalog products and categories installed."
      ),
      loadingLabel: nextAction.loadingKey ? translate(nextAction.loadingKey, "Installing\u2026") : translate("upgrades.loading", "Installing\u2026")
    }] : [];
    return NextResponse.json({ version, actions: payload });
  } catch (error) {
    logger.error("failed to load upgrade actions", { component: "upgrade-actions", err: error });
    return NextResponse.json({ error: "Failed to load upgrade actions" }, { status: 500 });
  }
}
async function POST(req) {
  if (!isUpgradeActionsEnabled()) {
    return NextResponse.json({ error: "Upgrade actions are disabled" }, { status: 403 });
  }
  const { translate } = await resolveTranslations();
  const scopedTranslate = (key, fallback, params) => translate(key, fallback, params);
  const scopeResult = await resolveScope(req, scopedTranslate);
  if (!scopeResult.scope) return scopeResult.error;
  let parsedBody;
  try {
    parsedBody = await req.json();
  } catch {
    parsedBody = null;
  }
  const parsed = runSchema.safeParse(parsedBody || {});
  if (!parsed.success) {
    return NextResponse.json({ error: "Invalid request body" }, { status: 400 });
  }
  const container = scopeResult.container ?? await createRequestContainer();
  const version = getCurrentVersion();
  try {
    const result = await executeUpgradeAction(container, {
      actionId: parsed.data.actionId,
      tenantId: scopeResult.scope.tenantId,
      organizationId: scopeResult.scope.organizationId,
      version
    });
    const successMessage = translate(
      result.action.successKey,
      "Example catalog products and categories installed."
    );
    return NextResponse.json({
      status: result.status,
      message: successMessage,
      version
    });
  } catch (error) {
    logger.error("failed to execute upgrade action", { component: "upgrade-actions", err: error });
    const message = translate("upgrades.runFailed", "We could not run this upgrade action.");
    const details = error instanceof Error ? error.message : null;
    return NextResponse.json({ error: message, details }, { status: 500 });
  }
}
const openApi = {
  tag: configsTag,
  summary: "Upgrade actions management",
  methods: {
    GET: {
      summary: "List pending upgrade actions",
      description: "Returns a list of pending upgrade actions for the current version. These are one-time setup tasks that need to be executed after upgrading to a new version. Requires organization and tenant context.",
      responses: [
        { status: 200, description: "List of pending upgrade actions", schema: upgradeActionsListResponseSchema }
      ],
      errors: [
        { status: 400, description: "Missing organization or tenant context", schema: configErrorSchema },
        { status: 401, description: "Unauthorized", schema: configErrorSchema },
        { status: 500, description: "Failed to load upgrade actions", schema: configErrorSchema }
      ]
    },
    POST: {
      summary: "Execute upgrade action",
      description: "Executes a specific upgrade action by ID. Typically used for one-time setup tasks like seeding example data after version upgrade. Returns execution status and localized success message.",
      requestBody: {
        contentType: "application/json",
        schema: executeUpgradeActionRequestSchema
      },
      responses: [
        { status: 200, description: "Upgrade action executed successfully", schema: executeUpgradeActionResponseSchema }
      ],
      errors: [
        { status: 400, description: "Invalid request body or missing context", schema: configErrorSchema },
        { status: 401, description: "Unauthorized", schema: configErrorSchema },
        { status: 403, description: "Upgrade actions are disabled", schema: configErrorSchema },
        { status: 500, description: "Failed to execute upgrade action", schema: configErrorSchema }
      ]
    }
  }
};
export {
  GET,
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
