import { RefreshTokenUseCase } from "@/contexts/auth/application";
import { ExpressController } from "@/core/common/presentation";
import { Token } from "../../domain";
import { IRefreshTokenPresenter } from "./refresh-token.presenter";

export class RefreshTokenController extends ExpressController {
  public constructor(
    private readonly refreshToken: RefreshTokenUseCase,
    private readonly presenter: IRefreshTokenPresenter
  ) {
    super();
  }

  async executeImpl() {
    //const tabId = String(this.req.headers["x-tab-id"]);
    const refreshTokenOrError = Token.create(String(this.req.body.refresh_token));

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

    const newRefreshTokenOrError = await this.refreshToken.execute(refreshTokenOrError.data);

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

    return this.created(this.presenter.toDto(newRefreshTokenOrError.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.internalServerError(message);
  }
}
