import { LoginUseCase } from "@/contexts/auth/application";
import { ExpressController } from "@/core/common/presentation";
import { LoginData } from "../../domain";
import { ILoginPresenter } from "./login.presenter";

export class LoginController extends ExpressController {
  public constructor(
    private readonly login: LoginUseCase,
    private readonly presenter: ILoginPresenter
  ) {
    super();
  }

  async executeImpl() {
    const loginDataOrError = LoginData.createFromPrimitives({
      email: this.req.body.email,
      plainPassword: this.req.body.password,
      tabId: String(this.req.headers["x-tab-id"]),
    });

    if (loginDataOrError.isFailure) {
      return this.clientError("Invalid input data", loginDataOrError.error);
    }

    const loginResultOrError = await this.login.execute(loginDataOrError.data);

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

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