import {
  CurrencyCode,
  UniqueID,
  UtcDate,
  ValidationErrorCollection,
  ValidationErrorDetail,
  extractOrPushError,
  maybeFromNullableVO,
} from "@repo/rdx-ddd";
import { Result } from "@repo/rdx-utils";
import { CreateCustomerInvoiceRequestDTO } from "../../../common";
import {
  CustomerInvoiceNumber,
  CustomerInvoiceProps,
  CustomerInvoiceSerie,
  CustomerInvoiceStatus,
} from "../../domain";
import { mapDTOToCustomerInvoiceItemsProps } from "./map-dto-to-customer-invoice-items-props";

/**
 * Convierte el DTO a las props validadas (CustomerInvoiceProps).
 * No construye directamente el agregado.
 *
 * @param dto - DTO con los datos de la factura de cliente
 * @returns 
 
 *
 */

export function mapDTOToCustomerInvoiceProps(dto: CreateCustomerInvoiceRequestDTO) {
  const errors: ValidationErrorDetail[] = [];

  const invoiceId = extractOrPushError(UniqueID.create(dto.id), "id", errors);

  const invoiceNumber = extractOrPushError(
    maybeFromNullableVO(dto.invoice_number, (value) => CustomerInvoiceNumber.create(value)),
    "invoice_number",
    errors
  );
  const invoiceSeries = extractOrPushError(
    maybeFromNullableVO(dto.series, (value) => CustomerInvoiceSerie.create(value)),
    "invoice_series",
    errors
  );
  const invoiceDate = extractOrPushError(
    UtcDate.createFromISO(dto.invoice_date),
    "invoice_date",
    errors
  );
  const operationDate = extractOrPushError(
    maybeFromNullableVO(dto.operation_date, (value) => UtcDate.createFromISO(value)),
    "operation_date",
    errors
  );

  const currencyCode = extractOrPushError(
    CurrencyCode.create(dto.currency_code),
    "currency",
    errors
  );

  // 🔄 Validar y construir los items de factura con helper especializado
  const itemsResult = mapDTOToCustomerInvoiceItemsProps(dto.items);
  if (itemsResult.isFailure) {
    return Result.fail(itemsResult.error);
  }

  if (errors.length > 0) {
    return Result.fail(new ValidationErrorCollection("Invoice dto mapping failed", errors));
  }

  const invoiceProps: CustomerInvoiceProps = {
    invoiceNumber: invoiceNumber!,
    series: invoiceSeries!,
    invoiceDate: invoiceDate!,
    operationDate: operationDate!,
    status: CustomerInvoiceStatus.createDraft(),
    currencyCode: currencyCode!,
  };

  return Result.ok({ id: invoiceId!, props: invoiceProps });

  /*if (hasNoUndefinedFields(invoiceProps)) {
    const invoiceOrError = CustomerInvoice.create(invoiceProps, invoiceId);
    if (invoiceOrError.isFailure) {
      return Result.fail(invoiceOrError.error);
    }
    return Result.ok(invoiceOrError.data);
  }

  return Result.fail(
    new ValidationErrorCollection([
      { path: "", message: "Error building from DTO: Some fields are undefined" },
    ])
  );*/
}
