import { NextResponse } from "next/server";
import { z } from "zod";
import { makeCrudRoute } from "@open-mercato/shared/lib/crud/factory";
import { ExchangeRate } from "../../data/entities.js";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { exchangeRateCreateSchema, exchangeRateUpdateSchema } from "../../data/validators.js";
import {
  createCurrenciesCrudOpenApi,
  createPagedListResponseSchema,
  defaultOkResponseSchema
} from "../openapi.js";
const routeMetadata = {
  GET: { requireAuth: true, requireFeatures: ["currencies.rates.view"] },
  POST: { requireAuth: true, requireFeatures: ["currencies.rates.manage"] },
  PUT: { requireAuth: true, requireFeatures: ["currencies.rates.manage"] },
  DELETE: { requireAuth: true, requireFeatures: ["currencies.rates.manage"] }
};
const metadata = routeMetadata;
const rawBodySchema = z.looseObject({});
const crud = makeCrudRoute({
  metadata: routeMetadata,
  orm: {
    entity: ExchangeRate,
    idField: "id",
    orgField: "organizationId",
    tenantField: "tenantId",
    softDeleteField: "deletedAt"
  },
  events: {
    module: "currencies",
    entity: "exchange_rate",
    persistent: true
  },
  actions: {
    create: {
      commandId: "currencies.exchange_rates.create",
      schema: rawBodySchema,
      mapInput: ({ parsed }) => parsed,
      response: ({ result }) => ({ id: String(result.exchangeRateId) }),
      status: 201
    },
    update: {
      commandId: "currencies.exchange_rates.update",
      schema: rawBodySchema,
      mapInput: ({ parsed }) => parsed,
      response: () => ({ ok: true })
    },
    delete: {
      commandId: "currencies.exchange_rates.delete",
      schema: rawBodySchema,
      mapInput: ({ raw, ctx }) => ({
        id: raw.query?.id,
        organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? void 0,
        tenantId: ctx.auth?.tenantId ?? void 0
      }),
      response: () => ({ ok: true })
    }
  }
});
const listQuerySchema = z.object({
  id: z.string().uuid().optional(),
  page: z.coerce.number().min(1).default(1),
  pageSize: z.coerce.number().min(1).max(100).default(50),
  sortField: z.enum(["fromCurrencyCode", "toCurrencyCode", "date", "createdAt", "updatedAt"]).optional(),
  sortDir: z.enum(["asc", "desc"]).optional(),
  fromCurrencyCode: z.string().optional(),
  toCurrencyCode: z.string().optional(),
  isActive: z.enum(["true", "false"]).optional(),
  source: z.string().optional(),
  type: z.enum(["buy", "sell"]).optional()
}).loose();
const toRow = (rate) => ({
  id: String(rate.id),
  fromCurrencyCode: String(rate.fromCurrencyCode),
  toCurrencyCode: String(rate.toCurrencyCode),
  rate: String(rate.rate),
  date: rate.date.toISOString(),
  source: String(rate.source),
  type: rate.type ?? null,
  isActive: !!rate.isActive,
  createdAt: rate.createdAt ? rate.createdAt.toISOString() : null,
  updatedAt: rate.updatedAt ? rate.updatedAt.toISOString() : null,
  organizationId: String(rate.organizationId),
  tenantId: String(rate.tenantId)
});
async function GET(req) {
  const auth = await getAuthFromRequest(req);
  if (!auth || !auth.tenantId || !auth.orgId && !auth.isSuperAdmin) {
    return NextResponse.json({ items: [], total: 0, page: 1, pageSize: 50, totalPages: 1 }, { status: 401 });
  }
  const url = new URL(req.url);
  const parsed = listQuerySchema.safeParse({
    id: url.searchParams.get("id") ?? void 0,
    page: url.searchParams.get("page") ?? void 0,
    pageSize: url.searchParams.get("pageSize") ?? void 0,
    sortField: url.searchParams.get("sortField") ?? void 0,
    sortDir: url.searchParams.get("sortDir") ?? void 0,
    fromCurrencyCode: url.searchParams.get("fromCurrencyCode") ?? void 0,
    toCurrencyCode: url.searchParams.get("toCurrencyCode") ?? void 0,
    isActive: url.searchParams.get("isActive") ?? void 0,
    source: url.searchParams.get("source") ?? void 0,
    type: url.searchParams.get("type") ?? void 0
  });
  if (!parsed.success) {
    return NextResponse.json({ items: [], total: 0, page: 1, pageSize: 50, totalPages: 1 }, { status: 400 });
  }
  const container = await createRequestContainer();
  const em = container.resolve("em");
  const { id, page, pageSize, sortField, sortDir, fromCurrencyCode, toCurrencyCode, isActive, source, type } = parsed.data;
  const where = {
    tenantId: auth.tenantId,
    deletedAt: null
  };
  if (auth.orgId) {
    where.organizationId = auth.orgId;
  }
  if (id) where.id = id;
  if (fromCurrencyCode) where.fromCurrencyCode = fromCurrencyCode;
  if (toCurrencyCode) where.toCurrencyCode = toCurrencyCode;
  if (source) where.source = source;
  if (type) where.type = type;
  if (isActive === "true") where.isActive = true;
  if (isActive === "false") where.isActive = false;
  const fieldMap = {
    fromCurrencyCode: "fromCurrencyCode",
    toCurrencyCode: "toCurrencyCode",
    date: "date",
    createdAt: "createdAt",
    updatedAt: "updatedAt"
  };
  const orderBy = {};
  if (sortField) {
    const mapped = fieldMap[sortField] || "date";
    orderBy[mapped] = sortDir === "desc" ? "DESC" : "ASC";
  } else {
    orderBy.date = "DESC";
  }
  const offset = (page - 1) * pageSize;
  const [rows, total] = await em.findAndCount(ExchangeRate, where, { orderBy, limit: pageSize, offset });
  const items = rows.map(toRow);
  const totalPages = Math.max(1, Math.ceil(total / pageSize));
  return NextResponse.json({ items, total, page, pageSize, totalPages });
}
const POST = crud.POST;
const PUT = crud.PUT;
const DELETE = crud.DELETE;
const exchangeRateListItemSchema = z.object({
  id: z.string().uuid(),
  fromCurrencyCode: z.string(),
  toCurrencyCode: z.string(),
  rate: z.string(),
  date: z.string(),
  source: z.string(),
  type: z.string().nullable(),
  isActive: z.boolean(),
  createdAt: z.string().nullable(),
  updatedAt: z.string().nullable(),
  organizationId: z.string().uuid(),
  tenantId: z.string().uuid()
});
const openApi = createCurrenciesCrudOpenApi({
  resourceName: "ExchangeRate",
  pluralName: "ExchangeRates",
  querySchema: listQuerySchema,
  listResponseSchema: createPagedListResponseSchema(exchangeRateListItemSchema),
  create: {
    schema: exchangeRateCreateSchema,
    description: "Creates a new exchange rate."
  },
  update: {
    schema: exchangeRateUpdateSchema,
    responseSchema: defaultOkResponseSchema,
    description: "Updates an existing exchange rate by id."
  },
  del: {
    schema: z.object({ id: z.string().uuid() }),
    responseSchema: defaultOkResponseSchema,
    description: "Deletes an exchange rate by id."
  }
});
export {
  DELETE,
  GET,
  POST,
  PUT,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
