import Joi from "joi";

import { QueryCriteriaService } from "@/contexts/common/application/services";
import { IServerError } from "@/contexts/common/domain/errors";
import { ExpressController } from "@/contexts/common/infrastructure/express";
import { ListQuotesResult, ListQuotesUseCase } from "@/contexts/sales/application";
import { Quote } from "@/contexts/sales/domain";
import {
  ICollection,
  IListQuotes_Response_DTO,
  IListResponse_DTO,
  IQueryCriteria,
  Result,
  RuleValidator,
} from "@shared/contexts";
import { ISalesContext } from "../../../../Sales.context";
import { IListQuotesPresenter } from "./presenter";

export class ListQuotesController extends ExpressController {
  private useCase: ListQuotesUseCase;
  private presenter: IListQuotesPresenter;
  private context: ISalesContext;

  constructor(
    props: {
      useCase: ListQuotesUseCase;
      presenter: IListQuotesPresenter;
    },
    context: ISalesContext
  ) {
    super();

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

  protected validateQuery(query): Result<any> {
    const schema = Joi.object({
      page: Joi.number().optional(),
      limit: Joi.number().optional(),
      $sort_by: Joi.string().optional(),
      $filters: Joi.string().optional(),
      q: Joi.string().optional(),
    }).optional();

    return RuleValidator.validate(schema, query);
  }

  async executeImpl() {
    const queryOrError = this.validateQuery(this.req.query);
    if (queryOrError.isFailure) {
      return this.clientError(queryOrError.error.message);
    }

    const queryParams = queryOrError.object;

    try {
      const queryCriteria: IQueryCriteria = QueryCriteriaService.parse(queryParams);

      const result: ListQuotesResult = await this.useCase.execute({
        queryCriteria,
      });

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

      const quotes = <ICollection<Quote>>result.object;

      return this.ok<IListResponse_DTO<IListQuotes_Response_DTO>>(
        this.presenter.mapArray(quotes, this.context, {
          page: queryCriteria.pagination.offset,
          limit: queryCriteria.pagination.limit,
        })
      );
    } catch (e: unknown) {
      return this.fail(e as IServerError);
    }
  }
}
