import { CreateInvoiceUseCase } from "@/contexts/invoices/application/create-invoice.use-case";
import { ExpressController, UniqueID } from "@/core";
import { ICreateInvoiceRequestDTO } from "../../dto";
import { ICreateInvoicePresenter } from "./presenter";

export class CreateInvoiceController extends ExpressController {
  public constructor(
    private readonly createInvoice: CreateInvoiceUseCase,
    private readonly presenter: ICreateInvoicePresenter
  ) {
    super();
  }

  protected async executeImpl() {
    const createDTO: ICreateInvoiceRequestDTO = this.req.body;

    // Validar ID
    const invoiceIdOrError = UniqueID.create(createDTO.id);
    if (invoiceIdOrError.isFailure) return this.invalidInputError("Invoice ID not valid");

    const invoiceOrError = await this.createInvoice.execute(invoiceIdOrError.data, createDTO);

    if (invoiceOrError.isFailure) {
      return this.handleError(invoiceOrError.error);
    }

    return this.ok(this.presenter.toDTO(invoiceOrError.data));
  }

  private handleError(error: Error) {
    const message = error.message;

    if (
      message.includes("Database connection lost") ||
      message.includes("Database request timed out")
    ) {
      return this.unavailableError(
        "Database service is currently unavailable. Please try again later."
      );
    }

    return this.conflictError(message);
  }
}
