import {
  IUseCase,
  IUseCaseError,
  IUseCaseRequest,
  UseCaseError,
} from "@/contexts/common/application";
import { IRepositoryManager } from "@/contexts/common/domain";
import { IInfrastructureError } from "@/contexts/common/infrastructure";
import { ISequelizeAdapter } from "@/contexts/common/infrastructure/sequelize";
import {
  Collection,
  CurrencyData,
  Description,
  DomainError,
  IDomainError,
  Language,
  Note,
  Percentage,
  Quantity,
  Result,
  TextValueObject,
  UTCDateValue,
  UniqueID,
  UnitPrice,
} from "@shared/contexts";

import { ArticleIdentifier } from "@/contexts/catalog/domain";
import { IUpdateQuote_Request_DTO } from "@shared/contexts";
import {
  Dealer,
  IQuoteRepository,
  Quote,
  QuoteCustomer,
  QuoteCustomerReference,
  QuoteItem,
  QuoteReference,
  QuoteStatus,
} from "../../domain";
import { ISalesContext } from "../../infrastructure";

export interface IUpdateQuoteUseCaseRequest extends IUseCaseRequest {
  id: UniqueID;
  quoteDTO: IUpdateQuote_Request_DTO;
}

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

export class UpdateQuoteUseCase
  implements IUseCase<IUpdateQuoteUseCaseRequest, Promise<UpdateQuoteResponseOrError>>
{
  private _adapter: ISequelizeAdapter;
  private _repositoryManager: IRepositoryManager;
  private _dealer?: Dealer;

  constructor(context: ISalesContext) {
    this._adapter = context.adapter;
    this._repositoryManager = context.repositoryManager;
    this._dealer = context.dealer;
  }

  async execute(request: IUpdateQuoteUseCaseRequest): Promise<UpdateQuoteResponseOrError> {
    const { id, quoteDTO } = request;
    const QuoteRepository = this._getQuoteRepository();

    // Validaciones de datos
    if (!this._dealer) {
      const message = "Error. Missing Dealer";
      return Result.fail(UseCaseError.create(UseCaseError.INVALID_INPUT_DATA, message));
    }

    const dealerId = this._dealer.id;

    // 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

    // Crear quote
    const quoteOrError = this._tryCreateQuoteInstance(quoteDTO, id, dealerId);

    if (quoteOrError.isFailure) {
      const { error: domainError } = quoteOrError;
      let errorCode = "";
      let message = "";

      switch (domainError.code) {
        // Errores manuales
        case DomainError.INVALID_INPUT_DATA:
          errorCode = UseCaseError.INVALID_INPUT_DATA;
          message = "El presupuesto tiene algún dato erróneo.";
          break;

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

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

    return this._updateQuote(quoteOrError.object);
  }

  private async _updateQuote(quote: Quote) {
    // Guardar el contacto
    const transaction = this._adapter.startTransaction();
    const quoteRepository = this._getQuoteRepository();
    let quoteRepo: IQuoteRepository;

    try {
      await transaction.complete(async (t) => {
        quoteRepo = quoteRepository({ transaction: t });
        await quoteRepo.update(quote);
      });

      return Result.ok<Quote>(quote);
    } catch (error: unknown) {
      const _error = error as IInfrastructureError;
      return Result.fail(UseCaseError.create(UseCaseError.REPOSITORY_ERROR, _error.message));
    }
  }

  private _tryCreateQuoteInstance(
    quoteDTO: IUpdateQuote_Request_DTO,
    quoteId: UniqueID,
    dealerId: UniqueID
  ): Result<Quote, IDomainError> {
    const statusOrError = QuoteStatus.create(quoteDTO.status);
    if (statusOrError.isFailure) {
      return Result.fail(statusOrError.error);
    }

    const dateOrError = UTCDateValue.create(quoteDTO.date);
    if (dateOrError.isFailure) {
      return Result.fail(dateOrError.error);
    }

    const referenceOrError = QuoteReference.create(quoteDTO.reference);
    if (referenceOrError.isFailure) {
      return Result.fail(referenceOrError.error);
    }

    const languageOrError = Language.createFromCode(quoteDTO.lang_code);
    if (languageOrError.isFailure) {
      return Result.fail(languageOrError.error);
    }

    const customerReferenceOrError = QuoteCustomerReference.create(quoteDTO.customer_reference);
    if (customerReferenceOrError.isFailure) {
      return Result.fail(customerReferenceOrError.error);
    }

    const customerOrError = QuoteCustomer.create(quoteDTO.customer_information);
    if (customerOrError.isFailure) {
      return Result.fail(customerOrError.error);
    }

    const currencyOrError = CurrencyData.createFromCode(quoteDTO.currency_code);
    if (currencyOrError.isFailure) {
      return Result.fail(currencyOrError.error);
    }

    const paymentOrError = Note.create(quoteDTO.payment_method);
    if (paymentOrError.isFailure) {
      return Result.fail(paymentOrError.error);
    }

    const notesOrError = TextValueObject.create(quoteDTO.notes);
    if (notesOrError.isFailure) {
      return Result.fail(notesOrError.error);
    }

    const validityOrError = Note.create(quoteDTO.validity);
    if (validityOrError.isFailure) {
      return Result.fail(validityOrError.error);
    }

    const discountOrError = Percentage.create(quoteDTO.discount);
    if (discountOrError.isFailure) {
      return Result.fail(discountOrError.error);
    }

    const taxOrError = Percentage.create(quoteDTO.tax);
    if (taxOrError.isFailure) {
      return Result.fail(taxOrError.error);
    }

    const dateSentOrError = UTCDateValue.create(null);
    if (dateSentOrError.isFailure) {
      return Result.fail(dateSentOrError.error);
    }

    // Items

    let items: Collection<QuoteItem>;

    try {
      items = new Collection<QuoteItem>(
        quoteDTO.items?.map((item) => {
          const idArticleOrError = ArticleIdentifier.create(item.id_article);
          if (idArticleOrError.isFailure) {
            throw idArticleOrError.error;
          }

          const descriptionOrError = Description.create(item.description);
          if (descriptionOrError.isFailure) {
            throw descriptionOrError.error;
          }

          const quantityOrError = Quantity.create({
            amount: item.quantity.amount,
            scale: item.quantity.scale,
          });
          if (quantityOrError.isFailure) {
            throw quantityOrError.error;
          }

          const unitPriceOrError = UnitPrice.create({
            amount: item.unit_price?.amount,
            currencyCode: item.unit_price?.currency_code,
            scale: item.unit_price?.scale,
          });
          if (unitPriceOrError.isFailure) {
            throw unitPriceOrError.error;
          }

          const percentageOrError = Percentage.create({
            amount: item.discount?.amount,
            scale: item.discount?.scale,
          });
          if (percentageOrError.isFailure) {
            throw percentageOrError.error;
          }

          const quoteItemOrError = QuoteItem.create({
            idArticle: idArticleOrError.object,
            description: descriptionOrError.object,
            quantity: quantityOrError.object,
            unitPrice: unitPriceOrError.object,
            discount: percentageOrError.object,
          });

          if (quoteItemOrError.isFailure) {
            throw quoteItemOrError.error;
          }

          return quoteItemOrError.object;
        })
      );
    } catch (e: unknown) {
      return Result.fail(e as IDomainError);
    }

    return Quote.create(
      {
        status: statusOrError.object,
        date: dateOrError.object,
        reference: referenceOrError.object,
        language: languageOrError.object,
        customerReference: customerReferenceOrError.object,
        customer: customerOrError.object,
        currency: currencyOrError.object,
        paymentMethod: paymentOrError.object,
        notes: notesOrError.object,
        validity: validityOrError.object,

        discount: discountOrError.object,
        tax: taxOrError.object,

        items,

        dealerId,

        dateSent: dateSentOrError.object,
      },
      quoteId
    );
  }

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