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 {
  runCrudMutationGuardAfterSuccess,
  validateCrudMutationGuard
} from "@open-mercato/shared/lib/crud/mutation-guard";
import { customerSettingsUpsertSchema } from "../../../data/validators.js";
import { loadCustomerSettings } from "../../../commands/settings.js";
import { withScopedPayload } from "../../utils.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
const SETTINGS_RESOURCE_KIND = "customers.settings";
const metadata = {
  GET: { requireAuth: true, requireFeatures: ["customers.settings.manage"] },
  PUT: { requireAuth: true, requireFeatures: ["customers.settings.manage"] }
};
async function resolveSettingsContext(req) {
  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 organizationId = scope?.selectedId ?? auth.orgId ?? null;
  if (!organizationId) {
    throw new CrudHttpError(400, { error: translate("customers.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
  };
  const em = container.resolve("em");
  return {
    ctx,
    tenantId: auth.tenantId,
    organizationId,
    translate,
    em
  };
}
async function GET(req) {
  try {
    const { em, tenantId, organizationId } = await resolveSettingsContext(req);
    const record = await loadCustomerSettings(em, { tenantId, organizationId });
    return NextResponse.json({
      addressFormat: record?.addressFormat ?? "line_first"
    });
  } catch (err) {
    if (isCrudHttpError(err)) {
      return NextResponse.json(err.body, { status: err.status });
    }
    const { translate } = await resolveTranslations();
    logger.error("customers.settings.address-format.get failed", { err });
    return NextResponse.json({ error: translate("customers.errors.lookup_failed", "Failed to load settings") }, { status: 400 });
  }
}
async function PUT(req) {
  try {
    const { ctx, tenantId, organizationId, translate } = await resolveSettingsContext(req);
    const payload = await req.json().catch(() => ({}));
    const scoped = withScopedPayload(payload, ctx, translate);
    const input = customerSettingsUpsertSchema.parse(scoped);
    const guardResult = await validateCrudMutationGuard(ctx.container, {
      tenantId,
      organizationId,
      userId: ctx.auth.sub,
      resourceKind: SETTINGS_RESOURCE_KIND,
      resourceId: organizationId,
      operation: "update",
      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 } = await commandBus.execute(
      "customers.settings.save",
      { input, ctx }
    );
    if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {
      await runCrudMutationGuardAfterSuccess(ctx.container, {
        tenantId,
        organizationId,
        userId: ctx.auth.sub,
        resourceKind: SETTINGS_RESOURCE_KIND,
        resourceId: organizationId,
        operation: "update",
        requestMethod: req.method,
        requestHeaders: req.headers,
        metadata: guardResult.metadata ?? null
      });
    }
    return NextResponse.json({
      addressFormat: result?.addressFormat ?? input.addressFormat
    });
  } catch (err) {
    if (isCrudHttpError(err)) {
      return NextResponse.json(err.body, { status: err.status });
    }
    const { translate } = await resolveTranslations();
    logger.error("customers.settings.address-format.put failed", { err });
    return NextResponse.json({ error: translate("customers.errors.save_failed", "Failed to save settings") }, { status: 400 });
  }
}
const addressFormatResponseSchema = z.object({
  addressFormat: z.string()
});
const addressFormatErrorSchema = z.object({
  error: z.string()
});
const openApi = {
  tag: "Customers",
  summary: "Customer address format settings",
  methods: {
    GET: {
      summary: "Retrieve address format",
      description: "Returns the current address formatting preference for the selected organization.",
      responses: [
        { status: 200, description: "Current address format", schema: addressFormatResponseSchema },
        { status: 401, description: "Unauthorized", schema: addressFormatErrorSchema },
        { status: 400, description: "Organization context missing", schema: addressFormatErrorSchema }
      ]
    },
    PUT: {
      summary: "Update address format",
      description: "Updates the address format preference for the selected organization.",
      requestBody: {
        contentType: "application/json",
        schema: customerSettingsUpsertSchema
      },
      responses: [
        { status: 200, description: "Updated address format", schema: addressFormatResponseSchema },
        { status: 401, description: "Unauthorized", schema: addressFormatErrorSchema },
        { status: 400, description: "Invalid payload or organization context", schema: addressFormatErrorSchema }
      ]
    }
  }
};
export {
  GET,
  PUT,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
