class Api::V1::Projects::Branches::UpdateDefaultBranchService < ApplicationService 
  include ActiveModel::Model

  attr_accessor :project, :token, :owner, :repo, :new_default_branch
  attr_accessor :gitea_data

  validates :new_default_branch, presence: true

  def initialize(project, new_default_branch, token=nil)
    @project = project 
    @owner = project&.owner.login 
    @repo = project&.identifier
    @new_default_branch = new_default_branch
    @token = token 
  end

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

    check_branch_exist
    update_project
    excute_data_to_gitea
    
    gitea_data
  end

  private 
  def request_params 
    {
      access_token: token 
    }
  end

  def request_body 
    {
      default_branch: new_default_branch
    }
  end

  def update_project 
    @project.attributes = request_body
    raise Error, '更新默认分支失败！' unless @project.save
  end

  def excute_data_to_gitea 
    @gitea_data = $gitea_client.patch_repos_by_owner_repo(owner, repo, {body: request_body.to_json, query: request_params}) rescue nil
    raise Error, '更新默认分支失败！' unless @gitea_data.is_a?(Hash)
  end

  def check_branch_exist
    result = $gitea_hat_client.get_repos_branch_name_set_by_owner_repo(owner, repo, {query: request_params}) rescue nil
    raise Error, '查询分支名称失败！' unless result.is_a?(Array)
    raise Error, '新默认分支不存在！' if !result.include?(@new_default_branch)
  end
end