import { UpdateAccountUseCase } from "@/contexts/accounts/application/update-account.use-case";
import { UniqueID } from "@/core/common/domain";
import { ExpressController } from "@/core/common/presentation";
import { IUpdateAccountRequestDTO } from "../../dto";
import { IUpdateAccountPresenter } from "./update-account.presenter";

export class UpdateAccountController extends ExpressController {
  public constructor(
    private readonly updateAccount: UpdateAccountUseCase,
    private readonly presenter: IUpdateAccountPresenter
  ) {
    super();
  }

  protected async executeImpl() {
    const { accountId } = this.req.params;
    const updateDTO: IUpdateAccountRequestDTO = this.req.body;

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

    const accountOrError = await this.updateAccount.execute(accountIdOrError.data, updateDTO);

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