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 { UpdateDealerResponseOrError, UpdateDealerUseCase } from "@/contexts/sales/application";
import { Dealer } from "@/contexts/sales/domain";
import {
  IUpdateDealer_Request_DTO,
  IUpdateDealer_Response_DTO,
  ensureIdIsValid,
  ensureUpdateDealer_Request_DTOIsValid,
} from "@shared/contexts";
import { ISalesContext } from "../../../../Sales.context";
import { IUpdateDealerPresenter } from "./presenter/UpdateDealer.presenter";

export class UpdateDealerController extends ExpressController {
  private useCase: UpdateDealerUseCase;
  private presenter: IUpdateDealerPresenter;
  private context: ISalesContext;

  constructor(
    props: {
      useCase: UpdateDealerUseCase;
      presenter: IUpdateDealerPresenter;
    },
    context: ISalesContext
  ) {
    super();

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

  async executeImpl() {
    try {
      const { dealerId } = this.req.params;
      const dealerDTO: IUpdateDealer_Request_DTO = this.req.body;

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

      // Validar DTO de datos
      const dealerDTOOrError = ensureUpdateDealer_Request_DTOIsValid(dealerDTO);

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

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

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

      const dealer = <Dealer>result.object;

      return this.ok<IUpdateDealer_Response_DTO>(this.presenter.map(dealer, 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 = "Dealer not found";

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

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

      case UseCaseError.INVALID_INPUT_DATA:
        errorMessage = "Dealer 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 dealer";
        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);
    }
  }
}
