import { IUseCaseError, UseCaseError } from "@/contexts/common/application/useCases";
import { ExpressController } from "@/contexts/common/infrastructure/express";

import { IServerError } from "@/contexts/common/domain/errors";
import { IInfrastructureError, InfrastructureError } from "@/contexts/common/infrastructure";
import { GetDealerByUserUseCase } from "@/contexts/sales/application";
import { Dealer } from "@/contexts/sales/domain";
import { IGetDealerResponse_DTO, ensureIdIsValid } from "@shared/contexts";
import { ISalesContext } from "../../../../Sales.context";
import { IGetDealerByUserPresenter } from "./presenter";

export class GetDealerByUserController extends ExpressController {
  private useCase: GetDealerByUserUseCase;
  private presenter: IGetDealerByUserPresenter;
  private context: ISalesContext;

  constructor(
    props: {
      useCase: GetDealerByUserUseCase;
      presenter: IGetDealerByUserPresenter;
    },
    context: ISalesContext
  ) {
    super();

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

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

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

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

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

      const dealer = <Dealer>result.object;

      return this.ok<IGetDealerResponse_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.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);
    }
  }
}
