import { UniqueID } from "@/core/common/domain";
import { ExpressController } from "@/core/common/presentation";
import { CreateAccountUseCase } from "../../../application";
import { ICreateAccountRequestDTO } from "../../dto";
import { ICreateAccountPresenter } from "./create-account.presenter";

export class CreateAccountController extends ExpressController {
  public constructor(
    private readonly createAccount: CreateAccountUseCase,
    private readonly presenter: ICreateAccountPresenter
  ) {
    super();
  }

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

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

    const accountOrError = await this.createAccount.execute(accountIdOrError.data, createDTO);

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