import { IUseCaseError, UseCaseError } from "@/contexts/common/application/useCases";
import { ExpressController } from "@/contexts/common/infrastructure/express";
import { GetUserUseCase } from "@/contexts/users/application";
import { User } from "@/contexts/users/domain/entities/User";
import { IGetUserResponse_DTO, ensureIdIsValid } from "@shared/contexts";

import { IServerError } from "@/contexts/common/domain/errors";
import { IInfrastructureError, InfrastructureError } from "@/contexts/common/infrastructure";
import { IUserContext } from "../../../User.context";
import { IGetUserPresenter } from "./presenter";

export class GetUserController extends ExpressController {
  private useCase: GetUserUseCase;
  private presenter: IGetUserPresenter;
  private context: IUserContext;

  constructor(
    props: {
      useCase: GetUserUseCase;
      presenter: IGetUserPresenter;
    },
    context: IUserContext
  ) {
    super();

    const { useCase, presenter } = props;
    this.useCase = useCase;
    this.presenter = presenter;
    this.context = context;
  }

  async executeImpl(): Promise<any> {
    const { userId } = this.req.params;

    // Validar ID
    const userIdOrError = ensureIdIsValid(userId);
    if (userIdOrError.isFailure) {
      const errorMessage = "User ID is not valid";
      const infraError = InfrastructureError.create(
        InfrastructureError.INVALID_INPUT_DATA,
        errorMessage,
        userIdOrError.error
      );
      return this.invalidInputError(errorMessage, infraError);
    }

    try {
      const result = await this.useCase.execute({
        id: userIdOrError.object,
      });

      if (result.isFailure) {
        return this._handleExecuteError(result.error);
      }

      const user = <User>result.object;

      return this.ok<IGetUserResponse_DTO>(this.presenter.map(user, this.context));
    } catch (e: unknown) {
      return this.fail(e as IServerError);
    }
  }

  private _handleExecuteError(error: IUseCaseError) {
    let errorMessage: string;
    let infraError: IInfrastructureError;

    switch (error.code) {
      case UseCaseError.NOT_FOUND_ERROR:
        errorMessage = "User not found";

        infraError = InfrastructureError.create(
          InfrastructureError.RESOURCE_NOT_FOUND_ERROR,
          errorMessage,
          error
        );

        return this.notFoundError(errorMessage, infraError);
        break;

      case UseCaseError.UNEXCEPTED_ERROR:
        errorMessage = error.message;

        infraError = InfrastructureError.create(
          InfrastructureError.UNEXCEPTED_ERROR,
          errorMessage,
          error
        );
        return this.internalServerError(errorMessage, infraError);
        break;

      default:
        errorMessage = error.message;
        return this.clientError(errorMessage);
    }
  }
}
