class Api::V1::Projects::Branches::ListService < ApplicationService 

  attr_accessor :project, :token, :owner, :repo, :name, :state, :page, :limit
  attr_accessor :gitea_data, :gitea_repo_data

  def initialize(project, params, token=nil)
    @project = project 
    @owner = project&.owner.login 
    @repo = project&.identifier 
    @token = token 
    @name = params[:name] 
    @state = params[:state]
    @page = params[:page] 
    @limit = params[:limit]
  end

  def call 
    load_gitea_data
    load_default_branch

    @gitea_data[:default_branch] = @gitea_repo_data["default_branch"]
    @gitea_data
  end

  private 
  def request_params 
    params = {
      access_token: token,
      page: page, 
      limit: limit
    }
    params.merge!({name: name}) if name.present? 
    params.merge!({state: state}) if state.present?
    
    params
  end

  def load_gitea_data 
    @gitea_data = $gitea_hat_client.get_repos_branches_by_owner_repo(owner, repo, {query: request_params}) rescue nil
    raise Error, '获取分支列表失败！' unless @gitea_data.is_a?(Hash)
  end

  def load_default_branch 
    @gitea_repo_data = $gitea_client.get_repos_by_owner_repo(owner, repo) rescue nil 
    raise Error, '获取仓库信息失败！' unless @gitea_data.is_a?(Hash)
  end
end