class Api::V1::Projects::BranchesController < Api::V1::BaseController 
  before_action :require_public_and_member_above, only: [:index, :all] 

  def gitee 
    url = URI("https://gitee.com/api/v5/repos/#{params[:owner]}/#{params[:repo]}/branches?access_token=#{params[:token]}&page=#{page}&per_page=#{limit}")
    https = Net::HTTP.new(url.host, url.port)
    https.use_ssl = true
    request = Net::HTTP::Get.new(url)
    response = https.request(request)
    render :json => response.read_body
  end

  def github 
    url = URI("https://api.github.com/repos/#{params[:owner]}/#{params[:repo]}/branches?page=#{page}&per_page=#{limit}")
    https = Net::HTTP.new(url.host, url.port)
    https.use_ssl = true

    request = Net::HTTP::Get.new(url)
    request["Authorization"] = "Bearer #{params[:token]}"
    request["Accept"] = "application/vnd.github+json"
    request["X-GitHub-Api-Version"] = "2022-11-28"

    response = https.request(request)
    render :json => response.read_body
  end

  def index 
    @result_object = Api::V1::Projects::Branches::ListService.call(@project, {name: params[:keyword], state: params[:state], page: page, limit: limit}, current_user&.gitea_token)
  end

  def all 
    @result_object = Api::V1::Projects::Branches::AllListService.call(@project, current_user&.gitea_token)
  end

  before_action :require_operate_above, only: [:create, :destroy, :restore] 

  def create 
    @result_object = Api::V1::Projects::Branches::CreateService.call(@project, branch_params, current_user&.gitea_token)
    @project.update_column(:updated_on, Time.now)
  end

  def destroy 
    @result_object = Api::V1::Projects::Branches::DeleteService.call(@project, params[:name], current_user&.gitea_token)
    if @result_object
      @project.update_column(:updated_on, Time.now)
      # 有开启的pr需要一同关闭
      # 1、删除本仓库中存在未关闭的pr,即本仓库分支1->分支2
      # 2、如果是fork仓库，考虑删除主仓库中存在未关闭的pr,即本仓库：分支1->主：分支2，同时分两种删除：1删除本仓库分支1，2删除主仓库分支2
      close_pull_requests_by(@project, params[:name])
      if @project.forked_from_project_id.present?
        # fork项目中删除分支
        close_pull_requests_by(@project.fork_project, params[:name])
      end

      return render_ok 
    else
      return render_error('删除分支失败!') 
    end
  end

  def restore 
    @result_object = Api::V1::Projects::Branches::RestoreService.call(@project, params[:branch_id], params[:branch_name], current_user&.gitea_token)
    if @result_object
      @project.update_column(:updated_on, Time.now)
      return render_ok 
    else 
      return render_error('恢复分支失败!')
    end
  end
  
  before_action :require_manager_above, only: [:update_default_branch] 

  def update_default_branch 
    @result_object = Api::V1::Projects::Branches::UpdateDefaultBranchService.call(@project, params[:name], current_user&.gitea_token)
    if @result_object
      @project.update_column(:updated_on, Time.now)
      return render_ok 
    else
      return render_error('更新默认分支失败!') 
    end
  end

  private 
  def branch_params 
    params.require(:branch).permit(:new_branch_name, :old_branch_name)
  end

  def close_pull_requests_by(project, branch_name)
    open_pull_requests = project.pull_requests.opening.where(head: branch_name).or(project.pull_requests.opening.where(base: branch_name))
    if open_pull_requests.present?
      open_pull_requests.each do |pull_request|
        closed = PullRequests::CloseService.call(project.owner, project.repository, pull_request, current_user)
        if closed === true
          pull_request.project_trends.create!(user: current_user, project: project,action_type: ProjectTrend::CLOSE)
          # 合并请求下issue处理为关闭
          pull_request.issue&.update_attributes!({status_id:5})
          SendTemplateMessageJob.perform_later('PullRequestClosed', current_user.id, pull_request.id) if Site.has_notice_menu?
        end
      end
    end
  end
end