import { IUseCaseError, UseCaseError } from "@/contexts/common/application";
import { IServerError } from "@/contexts/common/domain/errors";
import {
  IInfrastructureError,
  InfrastructureError,
} from "@/contexts/common/infrastructure";
import { ExpressController } from "@/contexts/common/infrastructure/express";
import {
  UpdateUserResponseOrError,
  UpdateUserUseCase,
} from "@/contexts/users/application";
import { User } from "@/contexts/users/domain";
import {
  IUpdateUser_Request_DTO,
  IUpdateUser_Response_DTO,
  ensureIdIsValid,
  ensureUpdateUser_Request_DTOIsValid,
} from "@shared/contexts";
import { IUserContext } from "../../../User.context";
import { IUpdateUserPresenter } from "./presenter/UpdateUser.presenter";

export class UpdateUserController extends ExpressController {
  private useCase: UpdateUserUseCase;
  private presenter: IUpdateUserPresenter;
  private context: IUserContext;

  constructor(
    props: {
      useCase: UpdateUserUseCase;
      presenter: IUpdateUserPresenter;
    },
    context: IUserContext,
  ) {
    super();

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

  async executeImpl() {
    try {
      const { userId } = this.req.params;
      const userDTO: IUpdateUser_Request_DTO = this.req.body;

      // 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);
      }

      // Validar DTO de datos
      const userDTOOrError = ensureUpdateUser_Request_DTOIsValid(userDTO);

      if (userDTOOrError.isFailure) {
        const errorMessage = "User data not valid";
        const infraError = InfrastructureError.create(
          InfrastructureError.INVALID_INPUT_DATA,
          errorMessage,
          userDTOOrError.error,
        );
        return this.invalidInputError(errorMessage, infraError);
      }

      // Llamar al caso de uso
      const result: UpdateUserResponseOrError = await this.useCase.execute({
        id: userIdOrError.object,
        userDTO,
      });

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

      const user = <User>result.object;

      return this.ok<IUpdateUser_Response_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.INVALID_INPUT_DATA:
        errorMessage = "User data not valid";

        infraError = InfrastructureError.create(
          InfrastructureError.INVALID_INPUT_DATA,
          "Datos del cliente a actulizar erróneos",
          error,
        );
        return this.invalidInputError(errorMessage, infraError);
        break;

      case UseCaseError.REPOSITORY_ERROR:
        errorMessage = "Error updating user";
        infraError = InfrastructureError.create(
          InfrastructureError.UNEXCEPTED_ERROR,
          errorMessage,
          error,
        );
        return this.conflictError(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);
    }
  }
}
