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 { UpdateProfileUseCase } from "@/contexts/profile/application";
import { User } from "@/contexts/users/domain";
import {
  IUpdateProfileResponse_DTO,
  IUpdateProfile_Request_DTO,
  ensureUpdateProfile_Request_DTOIsValid,
} from "@shared/contexts";
import { IProfileContext } from "../../../Profile.context";
import { IUpdateProfilePresenter } from "./presenter";

import { Request } from "express";

interface AuthenticatedRequest extends Request {
  user?: User;
}

export class UpdateProfileController extends ExpressController {
  private useCase: UpdateProfileUseCase;
  private presenter: IUpdateProfilePresenter;
  private context: IProfileContext;

  constructor(
    props: {
      useCase: UpdateProfileUseCase;
      presenter: IUpdateProfilePresenter;
    },
    context: IProfileContext
  ) {
    super();

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

  async executeImpl() {
    const req = this.req as AuthenticatedRequest;
    const user = <User>req.user;

    if (!user) {
      const errorMessage = "Unexpected missing Profile data";
      const infraError = InfrastructureError.create(
        InfrastructureError.UNEXCEPTED_ERROR,
        errorMessage
      );
      return this.internalServerError(errorMessage, infraError);
    }

    try {
      const profileDTO: IUpdateProfile_Request_DTO = this.req.body;

      // Validar DTO de datos
      const ProfileDTOOrError = ensureUpdateProfile_Request_DTOIsValid(profileDTO);

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

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

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

      const profile = result.object;

      return this.ok<IUpdateProfileResponse_DTO>(this.presenter.map(profile, 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 has no associated profile";

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

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

      case UseCaseError.INVALID_INPUT_DATA:
        errorMessage = "Profile data not valid";

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

      case UseCaseError.REPOSITORY_ERROR:
        errorMessage = "Error updating profile";
        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);
    }
  }
}
