class ExaminationBankQuery < ApplicationQuery
  include CustomSortable
  attr_reader :params

  sort_columns :updated_at, default_by: :updated_at, default_direction: :desc, default_table: 'examination_banks'

  def initialize(params)
    @params = params
  end

  def call
    if params[:public].to_i == 1
      exams = ExaminationBank.where(public: 1)
    elsif params[:public].to_i == 0
      exams = ExaminationBank.where(user_id: User.current.id)
    end

    if params[:tag_discipline_id].present?
      exams = exams.joins(:tag_discipline_containers).where(tag_discipline_containers: {tag_discipline_id: params[:tag_discipline_id]})
    elsif params[:sub_discipline_id].present?
      exams = exams.where(sub_discipline_id: params[:sub_discipline_id])
    elsif params[:discipline_id].present?
      exams = exams.joins(:sub_discipline).where(sub_disciplines: {discipline_id: params[:discipline_id]})
    end

    exams = exams.where(difficulty: params[:difficulty].to_i) if params[:difficulty].present?

    exams = exams.where("name like ?", "%#{params[:keyword].strip}%") if params[:keyword].present?

    custom_sort(exams, params[:sort_by], params[:sort_direction])
  end
end