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

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

  validates :branch_name, presence: true

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

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

    check_branch_exist
    excute_data_to_gitea
    
    true
  end

  private 
  def request_params 
    {
      access_token: token 
    }
  end

  def excute_data_to_gitea 
    begin
      @gitea_data = $gitea_client.delete_repos_branches_by_owner_repo_branch(owner, repo, CGI.escape(branch_name), {query: request_params}) 
    rescue => e
      raise Error, '保护分支无法删除！' if e.to_s.include?("branch protected")
      raise Error, '删除分支失败！'
    end
  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?(@branch_name)
  end
end