class Api::V1::Projects::Pulls::PullsController < Api::V1::BaseController
  before_action :require_public_and_member_above

  def index  
    @pulls = Api::V1::Projects::Pulls::ListService.call(@project, query_params)
    @pulls = kaminari_paginate(@pulls)
  end

  before_action :load_pull_request, only: [:show, :reopen, :files] 

  def show 
   @result_object = Api::V1::Projects::Pulls::GetService.call(@project, @pull_request, current_user&.gitea_token)
   @last_review = @pull_request.reviews.order(created_at: :desc).take
  end

  def reopen
    can_merge = @project&.pull_requests.where(head: @pull_request.head, base: @pull_request.base, status: 0, is_original: @pull_request.is_original, fork_project_id: @pull_request.fork_project_id)
    if can_merge.present?
      render json: {
        status: -1,
        redirect_url:"/#{@project.owner.login}/#{@project.identifier}/pulls/#{can_merge.first.gitea_number}", 
        message: "在这些分支之间的合并请求已存在",
      }
    else
      @result_object = Api::V1::Projects::Pulls::ReopenService.call(@project, @pull_request, current_user)
      if @result_object
        ProjectActions::PullRequestEvent.build(@project, current_user, @pull_request, "reopened") 
        render_ok
      else
        render_error("合并请求重新打开失败！")
      end
    end
  end

  def files
    if params[:filepath].present? 
      @result_object = $gitea_hat_client.get_repos_pulls_files_by_owner_repo_index_filepath(@project&.owner.login, @project&.identifier, @pull_request.gitea_number, CGI.escape(params[:filepath]), {query: {token: current_user&.gitea_token}})
    else
      @result_object = $gitea_hat_client.get_repos_pulls_files_by_owner_repo_index(@project&.owner.login, @project&.identifier, @pull_request.gitea_number, {query: {isNew: "true",token: current_user&.gitea_token, page: page, limit: limit}})
    end
  end 

  private 
  def query_params 
    params.permit(:status, :keyword, :priority_id, :issue_tag_id, :version_id, :reviewer_id, :sort_by, :sort_direction)
  end
end