class Api::V1::Projects::Git::TreesService < ApplicationService 
  include ActiveModel::Model

  attr_accessor :project, :token, :sha, :recursive, :page, :limit, :owner, :repo 
  attr_accessor :gitea_data 
  
  validates :sha, presence: :true
  validates :recursive, inclusion: {in: [nil, '', true, false]}

  def initialize(project, sha, params, token=nil) 
    @project = project 
    @owner = project&.owner.login 
    @repo = project&.identifier 
    @token = token
    @sha = sha
    @recursive = params[:recursive]
    @page = params[:page] || 1
    @limit = params[:limit] || 15
  end

  def call 
    raise Error, errors.full_messages.join(", ") unless valid?
    $gitea_client.token = token unless token.blank? 
    load_gitea_data 

    $gitea_client.token = nil unless token.blank? 
    gitea_data
  end

  private 
  def request_query 
    if recursive.present? 
      {
        recursive: recursive,
        page: page,
        per_page: limit,
        access_token: token
      }
    else 
      {
        page: page,
        per_page: limit,
        access_token: token
      }
    end
  end

  def load_gitea_data
    @gitea_data = $gitea_client.get_repos_git_trees_by_owner_repo_sha(owner, repo, sha, {query: request_query}) rescue nil
    raise Error, '获取文件树列表失败！' unless @gitea_data.is_a?(Hash)
  end
end