import { Presenter } from "@erp/core/api";
import { DomainValidationError, toEmptyString } from "@repo/rdx-ddd";
import { GetCustomerInvoiceByIdResponseDTO } from "../../../../common/dto";
import { CustomerInvoice, InvoiceRecipient } from "../../../domain";

type GetRecipientInvoiceByInvoiceIdResponseDTO = GetCustomerInvoiceByIdResponseDTO["recipient"];

export class RecipientInvoiceFullPresenter extends Presenter {
  toOutput(invoice: CustomerInvoice): GetRecipientInvoiceByInvoiceIdResponseDTO {
    if (!invoice.recipient) {
      throw DomainValidationError.requiredValue("recipient", {
        cause: invoice,
      });
    }

    return invoice.recipient.match(
      (recipient: InvoiceRecipient) => {
        return {
          id: invoice.customerId.toString(),
          name: recipient.name.toString(),
          tin: recipient.tin.toString(),
          street: toEmptyString(recipient.street, (value) => value.toString()),
          street2: toEmptyString(recipient.street2, (value) => value.toString()),
          city: toEmptyString(recipient.city, (value) => value.toString()),
          province: toEmptyString(recipient.province, (value) => value.toString()),
          postal_code: toEmptyString(recipient.postalCode, (value) => value.toString()),
          country: toEmptyString(recipient.country, (value) => value.toString()),
        };
      },
      () => {
        return {
          id: "",
          name: "",
          tin: "",
          street: "",
          street2: "",
          city: "",
          province: "",
          postal_code: "",
          country: "",
        };
      }
    );
  }
}
