// Ejemplo: regla específica para Billing → InvoiceIdAlreadyExistsError
// (si defines un error más ubicuo dentro del BC con su propia clase)

import {
  ApiErrorMapper,
  ConflictApiError,
  ErrorToApiRule,
  ValidationApiError,
} from "@erp/core/api";
import {
  CustomerInvoiceIdAlreadyExistsError,
  EntityIsNotProformaError,
  isCustomerInvoiceIdAlreadyExistsError,
  isEntityIsNotProformaError,
  isProformaCannotBeConvertedToInvoiceError,
  ProformaCannotBeConvertedToInvoiceError,
} from "../../domain";

// Crea una regla específica (prioridad alta para sobreescribir mensajes)
const invoiceDuplicateRule: ErrorToApiRule = {
  priority: 120,
  matches: (e) => isCustomerInvoiceIdAlreadyExistsError(e),
  build: (e) =>
    new ConflictApiError(
      (e as CustomerInvoiceIdAlreadyExistsError).message ||
        "Invoice with the provided id already exists."
    ),
};

const entityIsNotProformaError: ErrorToApiRule = {
  priority: 120,
  matches: (e) => isEntityIsNotProformaError(e),
  build: (e) =>
    new ValidationApiError(
      (e as EntityIsNotProformaError).message || "Entity with the provided id is not proforma"
    ),
};

const proformaConversionRule: ErrorToApiRule = {
  priority: 120,
  matches: (e) => isProformaCannotBeConvertedToInvoiceError(e),
  build: (e) =>
    new ValidationApiError(
      (e as ProformaCannotBeConvertedToInvoiceError).message ||
        "Proforma cannot be converted to an Invoice."
    ),
};

// Cómo aplicarla: crea una nueva instancia del mapper con la regla extra
export const customerInvoicesApiErrorMapper: ApiErrorMapper = ApiErrorMapper.default()
  .register(invoiceDuplicateRule)
  .register(entityIsNotProformaError)
  .register(proformaConversionRule);
