class Api::V1::Projects::Pulls::ListService < ApplicationService
  include ActiveModel::Model

  attr_reader :project, :keyword, :status, :priority_id, :issue_tag_id, :version_id, :reviewer_id, :assign_user_id, :sort_by, :sort_direction 
  attr_accessor :queried_pull_requests

  validates :status, inclusion: {in: [0, 1, 2], message: "请输入正确的Status"}, allow_nil: true
  validates :sort_by, inclusion: {in: PullRequest.column_names, message: '请输入正确的SortBy'}
  validates :sort_direction, inclusion: {in: %w(asc desc), message: '请输入正确的SortDirection'}

  def initialize(project, params={})
    @project = project 
    @keyword = params[:keyword]
    @status = params[:status].present? ? params[:status].to_i : nil
    @priority_id = params[:priority_id]
    @issue_tag_id = params[:issue_tag_id]
    @version_id = params[:version_id]
    @reviewer_id = params[:reviewer_id]
    @assign_user_id = params[:assign_user_id]
    @sort_by = params[:sort_by] || 'created_at'
    @sort_direction = params[:sort_direction] || 'desc'
  end

  def call 
    raise Error, errors.full_messages.join(",") unless valid? 
    pull_request_query_data

    queried_pull_requests
  end

  private 
  def pull_request_query_data 
    pull_requests = @project.pull_requests

    pull_requests = pull_requests.where(status: status) if status.present? 
    pull_requests = pull_requests.where(issues: {priority_id: priority_id}) if priority_id.present?
    pull_requests = pull_requests.where(issue_tags: {id: issue_tag_id}) if issue_tag_id.present? 
    pull_requests = pull_requests.where(issues: {fixed_version_id: version_id}) if version_id.present?
    pull_requests = pull_requests.where(users: {id: reviewer_id}) if reviewer_id.present? 
    pull_requests = pull_requests.where(issues: {assigned_to_id: assign_user_id}) if assign_user_id.present?
    
    q = pull_requests.ransack(title_or_body_cont: keyword)
    scope = q.result.includes(:fork_project, :journals, :reviews, :reviewers, issue: [:journals, :priority, :version, :issue_tags])
    scope = scope.order("pull_requests.#{sort_by} #{sort_direction}")

    @queried_pull_requests = scope
  end
end