import { LogoutUseCase } from "@/contexts/auth/application/logout";
import { TabContextRequest } from "@/contexts/auth/infraestructure/express/types";
import { ExpressController } from "@/core/common/presentation";
import { AuthenticatedUser, LogoutData, TabContext } from "../../domain";

export class LogoutController extends ExpressController {
  public constructor(private readonly logout: LogoutUseCase) {
    super();
  }

  async executeImpl() {
    const user = this.req.user as AuthenticatedUser;
    const tabContext = (this.req as TabContextRequest).tabContext as TabContext;

    const logoutDataOrError = LogoutData.create({
      email: user.email,
      tabId: tabContext.tabId,
    });

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

    const logoutOrError = await this.logout.execute(logoutDataOrError.data);

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

    // Habría que invalidar el token del cliente

    return this.ok();
  }

  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.clientError(message);
  }
}
