import { IPresenterRegistry, ITransactionManager } from "@erp/core/api";
import { UniqueID } from "@repo/rdx-ddd";
import { Result } from "@repo/rdx-utils";
import { Transaction } from "sequelize";
import { VerifactuRecordService } from "../../../domain";

type SendInvoiceUseCaseInput = {
  invoice_id: string;
};

export class SendInvoiceUseCase {
  constructor(
    private readonly service: VerifactuRecordService,
    private readonly transactionManager: ITransactionManager,
    private readonly presenterRegistry: IPresenterRegistry
  ) {}

  public async execute(params: SendInvoiceUseCaseInput) {
    const { invoice_id } = params;
    console.log("CASO DE USO -----ESTO ES UNA PRUEBA>>>>>>", invoice_id);
    const idOrError = UniqueID.create(invoice_id);

    if (idOrError.isFailure) {
      return Result.fail(idOrError.error);
    }

    const invoiceId = idOrError.data;
    console.log("CASO DE USO -----VALIDADO>>>>>>", invoiceId);
    return this.transactionManager.complete(async (transaction: Transaction) => {
      try {
        console.log(
          "CASO DE USO -----LLamar servicio de invoices para recuperar el invoice>>>>>>",
          invoiceId
        );
        const invoice = {
          serie: "A",
          numero: "1",
          fecha_expedicion: "12-09-2025",
          tipo_factura: "F1",
          descripcion: "Venta de bienes",
          nif: "A15022510",
          nombre: "Empresa de prueba SL",
          lineas: [
            {
              base_imponible: "200",
              tipo_impositivo: "21",
              cuota_repercutida: "42",
            },
            {
              base_imponible: "100",
              tipo_impositivo: "10",
              cuota_repercutida: "10",
            },
          ],
          importe_total: "352.00",
        };
        const invoiceOrError = await this.service.sendInvoiceToVerifactu(invoice, transaction);
        if (invoiceOrError.isFailure) {
          return Result.fail(invoiceOrError.error);
        }

        const invoice2 = invoiceOrError.data;
        return Result.ok({});
      } catch (error: unknown) {
        return Result.fail(error as Error);
      }
    });
  }
}
