import { GetCustomerInvoiceUseCase } from "@/contexts/customer-billing/application";
import { UniqueID } from "@/core/common/domain";
import { ExpressController } from "@/core/common/presentation";
import { IGetCustomerInvoicePresenter } from "./get-customer-invoice.presenter";

export class GetCustomerInvoiceController extends ExpressController {
  public constructor(
    private readonly getCustomerInvoice: GetCustomerInvoiceUseCase,
    private readonly presenter: IGetCustomerInvoicePresenter
  ) {
    super();
  }

  protected async executeImpl() {
    const { invoiceId } = this.req.params;

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

    const invoiceOrError = await this.getCustomerInvoice.execute(invoiceIdOrError.data);

    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);
  }
}
