module Comee
  module Core
    class QuotationRequestsController < ApplicationController
      include Common

      def index
        super do
          QuotationRequest.includes(:client).all
        end
      end

      def filter
        query = QuotationRequest.ransack(params[:q])
        render json: {success: true, data: serialize(query.result.includes(:client))}
      end

      def rfq_products_for_client
        client_products = ClientPrice.includes(:product).where(client_id: params[:id]).map(&:product_id)
        root = Product.roots.first
        ids = root.indirect_ids - client_products
        products = Product.where(id: ids)
        render json: {success: true, data: serialize(products)}
      end

      def create_request_with_items
        service = QuotationRequestService.new
        result = service.create_request_with_items(rfq_params.to_h)
        render json: {success: true, data: serialize(result)}
      end

      def submit
        service = QuotationRequestService.new
        rfq = service.submit(params[:id])
        render json: {success: true, data: serialize(rfq)}
      rescue StandardError => e
        render json: {success: false, error: e.message}
      end

      def submit_for_confirmation
        service = QuotationRequestService.new
        rfq = service.submit_for_confirmation(params[:id])
        render json: {success: true, data: serialize(rfq)}
      rescue StandardError => e
        render json: {success: false, error: e.message}
      end

      def confirm
        service = QuotationRequestService.new
        rfq = service.confirm(params[:id])
        render json: {success: true, data: serialize(rfq)}
      rescue StandardError => e
        render json: {success: false, error: e.message}
      end

      private

      def model_params
        params.require(:payload).permit(:reference_no, :status, :client_id)
      end

      def rfq_params
        params.require(:payload).permit(:client_id, items: %i[product_id unit_id quantity expected_delivery_date])
      end
    end
  end
end