import {
  IUseCaseError,
  UseCaseError,
} from "@/contexts/common/application/useCases";
import { IServerError } from "@/contexts/common/domain/errors";
import {
  IInfrastructureError,
  InfrastructureError,
} from "@/contexts/common/infrastructure";
import { ExpressController } from "@/contexts/common/infrastructure/express";
import { DeleteUserUseCase } from "@/contexts/users/application";
import { ensureIdIsValid } from "@shared/contexts";
import { IUserContext } from "../../../User.context";

export class DeleteUserController extends ExpressController {
  private useCase: DeleteUserUseCase;
  private context: IUserContext;

  constructor(props: { useCase: DeleteUserUseCase }, context: IUserContext) {
    super();

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

  async executeImpl(): Promise<any> {
    try {
      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);
      }

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

      if (result.isFailure) {
        return this._handleExecuteError(result.error);
      }
      return this.noContent();
    } 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);
    }
  }
}
