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

  attr_reader :project, :pull_request, :issue, :user


  def initialize(project, pull_request, user)
    @project = project
    @pull_request = pull_request
    @issue = pull_request&.issue
    @user = user
  end

  def call
    raise Error, "参数错误" unless valid?
    if gitea_change_status
      @pull_request.update_column(:status, PullRequest::OPEN)
      @pull_request&.project_trends&.where(action_type: ProjectTrend::CLOSE).destroy_all
      @issue.update_column(:status_id, IssueStatus::ADD)

      return true
    else
      raise Error, 'gitea change status failed'
    end
  end

  private
  def valid?
    return false if @project.blank? || @pull_request.blank? || @issue.blank? || @user.blank?
    return false unless @pull_request.closed?
    return true
  end

  def gitea_change_status
    gitea_result = Gitea::PullRequest::ChangeStatusService.call(@project.owner.login, @project.identifier, @pull_request.gitea_number, false, @user&.gitea_token) 
    return true if gitea_result[:status] == :success
    return false
  end
end