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 { DeleteDealerUseCase } from "@/contexts/sales/application";
import { ensureIdIsValid } from "@shared/contexts";
import { ISalesContext } from "../../../../Sales.context";

export class DeleteDealerController extends ExpressController {
  private useCase: DeleteDealerUseCase;
  private context: ISalesContext;

  constructor(props: { useCase: DeleteDealerUseCase }, context: ISalesContext) {
    super();

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

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

      // Llamar al caso de uso
      const result = await this.useCase.execute({
        id: dealerIdOrError.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 = "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);
    }
  }
}
