import { NextResponse } from "next/server";
import { z } from "zod";
import { makeCrudRoute } from "@open-mercato/shared/lib/crud/factory";
import { Currency } from "../../data/entities.js";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { escapeLikePattern } from "@open-mercato/shared/lib/db/escapeLikePattern";
import { currencyCreateSchema, currencyUpdateSchema } from "../../data/validators.js";
import {
  createCurrenciesCrudOpenApi,
  createPagedListResponseSchema,
  defaultOkResponseSchema
} from "../openapi.js";
const routeMetadata = {
  GET: { requireAuth: true, requireFeatures: ["currencies.view"] },
  POST: { requireAuth: true, requireFeatures: ["currencies.manage"] },
  PUT: { requireAuth: true, requireFeatures: ["currencies.manage"] },
  DELETE: { requireAuth: true, requireFeatures: ["currencies.manage"] }
};
const metadata = routeMetadata;
const rawBodySchema = z.object({}).loose();
const crud = makeCrudRoute({
  metadata: routeMetadata,
  orm: {
    entity: Currency,
    idField: "id",
    orgField: "organizationId",
    tenantField: "tenantId",
    softDeleteField: "deletedAt"
  },
  events: {
    module: "currencies",
    entity: "currency",
    persistent: true
  },
  actions: {
    create: {
      commandId: "currencies.currencies.create",
      schema: rawBodySchema,
      mapInput: ({ parsed }) => parsed,
      response: ({ result }) => ({ id: String(result.currencyId) }),
      status: 201
    },
    update: {
      commandId: "currencies.currencies.update",
      schema: rawBodySchema,
      mapInput: ({ parsed }) => parsed,
      response: () => ({ ok: true })
    },
    delete: {
      commandId: "currencies.currencies.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.uuid().optional(),
  page: z.coerce.number().min(1).default(1),
  pageSize: z.coerce.number().min(1).max(100).default(50),
  search: z.string().optional(),
  sortField: z.enum(["code", "name", "createdAt", "updatedAt"]).optional(),
  sortDir: z.enum(["asc", "desc"]).optional(),
  isBase: z.enum(["true", "false"]).optional(),
  isActive: z.enum(["true", "false"]).optional(),
  code: z.string().optional()
}).loose();
const toRow = (currency) => ({
  id: String(currency.id),
  code: String(currency.code),
  name: String(currency.name),
  symbol: currency.symbol ?? null,
  decimalPlaces: currency.decimalPlaces,
  thousandsSeparator: currency.thousandsSeparator ?? null,
  decimalSeparator: currency.decimalSeparator ?? null,
  isBase: !!currency.isBase,
  isActive: !!currency.isActive,
  createdAt: currency.createdAt ? currency.createdAt.toISOString() : null,
  updatedAt: currency.updatedAt ? currency.updatedAt.toISOString() : null,
  organizationId: String(currency.organizationId),
  tenantId: String(currency.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,
    search: url.searchParams.get("search") ?? void 0,
    sortField: url.searchParams.get("sortField") ?? void 0,
    sortDir: url.searchParams.get("sortDir") ?? void 0,
    isBase: url.searchParams.get("isBase") ?? void 0,
    isActive: url.searchParams.get("isActive") ?? void 0,
    code: url.searchParams.get("code") ?? 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, search, sortField, sortDir, isBase, isActive, code } = parsed.data;
  const filter = {
    tenantId: auth.tenantId,
    deletedAt: null
  };
  if (auth.orgId) {
    filter.organizationId = auth.orgId;
  }
  if (id) filter.id = id;
  if (code) filter.code = code;
  if (search) {
    filter.$or = [
      { code: { $ilike: `%${escapeLikePattern(search)}%` } },
      { name: { $ilike: `%${escapeLikePattern(search)}%` } },
      { symbol: { $ilike: `%${escapeLikePattern(search)}%` } }
    ];
  }
  if (isBase === "true") filter.isBase = true;
  if (isBase === "false") filter.isBase = false;
  if (isActive === "true") filter.isActive = true;
  if (isActive === "false") filter.isActive = false;
  const fieldMap = {
    code: "code",
    name: "name",
    createdAt: "createdAt",
    updatedAt: "updatedAt"
  };
  const orderBy = {};
  if (sortField) {
    const mapped = fieldMap[sortField] || "code";
    orderBy[mapped] = sortDir === "desc" ? "DESC" : "ASC";
  } else {
    orderBy.code = "ASC";
  }
  const offset = (page - 1) * pageSize;
  const [rows, total] = await em.findAndCount(Currency, filter, { 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 currencyListItemSchema = z.object({
  id: z.uuid(),
  code: z.string(),
  name: z.string(),
  symbol: z.string().nullable(),
  decimalPlaces: z.number(),
  thousandsSeparator: z.string().nullable(),
  decimalSeparator: z.string().nullable(),
  isBase: z.boolean(),
  isActive: z.boolean(),
  createdAt: z.string().nullable(),
  updatedAt: z.string().nullable(),
  organizationId: z.uuid(),
  tenantId: z.uuid()
});
const openApi = createCurrenciesCrudOpenApi({
  resourceName: "Currency",
  pluralName: "Currencies",
  querySchema: listQuerySchema,
  listResponseSchema: createPagedListResponseSchema(currencyListItemSchema),
  create: {
    schema: currencyCreateSchema,
    description: "Creates a new currency."
  },
  update: {
    schema: currencyUpdateSchema,
    responseSchema: defaultOkResponseSchema,
    description: "Updates an existing currency by id."
  },
  del: {
    schema: z.object({ id: z.string().uuid() }),
    responseSchema: defaultOkResponseSchema,
    description: "Deletes a currency by id."
  }
});
export {
  DELETE,
  GET,
  POST,
  PUT,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
