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

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

  validates :tag_name, presence: true

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

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

    check_tag_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_tags_by_owner_repo_tag(owner, repo, CGI.escape(tag_name), {query: request_params})
    rescue => e
      raise Error, '请先删除发行版！' if e.to_s.include?("409")
      raise Error, '删除标签失败！'
    end
  end

  def check_tag_exist
    result = $gitea_hat_client.get_repos_tag_name_set_by_owner_repo(owner, repo, {query: request_params}) rescue nil
    raise Error, '查询标签名称失败！' unless result.is_a?(Array)
    raise Error, '标签不存在！' if !result.include?(@tag_name)
  end
end