import { RegisterUseCase } from "@/contexts/auth/application";
import { ExpressController } from "@/core/common/presentation";
import { RegisterData } from "../../domain";
import { IRegisterPresenter } from "./register.presenter";

export class RegisterController extends ExpressController {
  public constructor(
    private readonly register: RegisterUseCase,
    private readonly presenter: IRegisterPresenter
  ) {
    super();
  }

  async executeImpl() {
    const registerDataOrError = RegisterData.createFromPrimitives({
      email: this.req.body.email,
      username: this.req.body.username,
      plainPassword: this.req.body.password,
    });

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

    const userOrError = await this.register.execute(registerDataOrError.data);

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

    return this.created(this.presenter.toDto(userOrError.data));
  }

  private handleError(error: Error) {
    const message = error.message;

    if (message.includes("User with this email or username already exists")) {
      return this.conflictError(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.internalServerError(message);
  }
}
