import { GetAccountUseCase } from "@/contexts/accounts/application";
import { UniqueID } from "@/core/common/domain";
import { ExpressController } from "@/core/common/presentation";
import { IGetAccountPresenter } from "./get-account.presenter";

export class GetAccountController extends ExpressController {
  public constructor(
    private readonly getAccount: GetAccountUseCase,
    private readonly presenter: IGetAccountPresenter
  ) {
    super();
  }

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

    // Validar ID
    const accountIdOrError = UniqueID.create(accountId);
    if (accountIdOrError.isFailure) return this.invalidInputError("Account ID not valid");

    const accountOrError = await this.getAccount.execute(accountIdOrError.data);

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

    return this.ok(this.presenter.toDTO(accountOrError.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);
  }
}
