import {
  IUseCase,
  IUseCaseError,
  IUseCaseRequest,
  UseCaseError,
} from "@/contexts/common/application/useCases";
import { IRepositoryManager } from "@/contexts/common/domain";
import { ISequelizeAdapter } from "@/contexts/common/infrastructure/sequelize";
import { DomainError, ISetStatusQuote_Request_DTO, Result, UniqueID } from "@shared/contexts";
import { IQuoteRepository, QuoteStatus } from "../../domain";

export interface ISetStatusQuoteUseCaseRequest extends IUseCaseRequest {
  id: UniqueID;
  newStatusDTO: ISetStatusQuote_Request_DTO;
}

export type SetStatusQuoteResponseOrError =
  | Result<never, IUseCaseError> // Misc errors (value objects)
  | Result<void, never>; // Success!

export class SetStatusQuoteUseCase
  implements IUseCase<ISetStatusQuoteUseCaseRequest, Promise<SetStatusQuoteResponseOrError>>
{
  private _adapter: ISequelizeAdapter;
  private _repositoryManager: IRepositoryManager;

  constructor(props: { adapter: ISequelizeAdapter; repositoryManager: IRepositoryManager }) {
    this._adapter = props.adapter;
    this._repositoryManager = props.repositoryManager;
  }

  async execute(request: ISetStatusQuoteUseCaseRequest): Promise<SetStatusQuoteResponseOrError> {
    const {
      id,
      newStatusDTO: { newStatus },
    } = request;

    const quoteRepository = this._getQuoteRepository();

    // Comprobar que existe el Quote
    const idExists = await quoteRepository().exists(id);
    if (!idExists) {
      const message = `Quote ID not found`;
      return Result.fail(
        UseCaseError.create(UseCaseError.NOT_FOUND_ERROR, message, {
          path: "id",
        })
      );
    }

    // //
    // regla de negocio -> no poder modificar un quote enviado

    // Comprobar el status
    const statusOrError = QuoteStatus.create(newStatus);
    if (statusOrError.isFailure) {
      const { error: domainError } = statusOrError;
      let errorCode = "";
      let message = "";

      switch (domainError.code) {
        // Errores manuales
        case DomainError.INVALID_INPUT_DATA:
          errorCode = UseCaseError.INVALID_INPUT_DATA;
          message = "Es nuevo estado no es correcto";
          break;

        default:
          errorCode = UseCaseError.UNEXCEPTED_ERROR;
          message = domainError.message;
          break;
      }

      return Result.fail(UseCaseError.create(errorCode, message, domainError));
    }

    const transaction = this._adapter.startTransaction();
    try {
      await transaction.complete(async (t) => {
        const quoteRepo = quoteRepository({ transaction: t });
        await quoteRepo.updateStatusById(id, statusOrError.object);
      });

      return Result.ok<void>();
    } catch (error: unknown) {
      //const _error = error as IInfrastructureError;
      return Result.fail(
        UseCaseError.create(
          UseCaseError.REPOSITORY_ERROR,
          "Error al establecer el nuevo estado en la cotización"
        )
      );
    }
  }

  private _getQuoteRepository() {
    return this._repositoryManager.getRepository<IQuoteRepository>("Quote");
  }
}
