class Api::V1::Projects::Commits::RecentService < ApplicationService
  
  attr_reader :project, :page, :limit, :keyword, :owner, :repo, :token 
  attr_accessor :gitea_data, :gitea_repo_detail

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

  def call 
    load_gitea_data
    load_gitea_repo_detail

    {result: gitea_data, detail:gitea_repo_detail} 
  end

  private
  def request_params
    param = {
      access_token: token,
      page: page,
      limit: limit,
      stats: false,
      files: false
    }
    param.merge!(keyword: keyword) if keyword.present?

    param 
  end

  def load_gitea_data
    @gitea_data = $gitea_hat_client.get_repos_recent_commits_by_owner_repo(owner, repo, {query: request_params}) rescue nil 
    raise Error, "获取最近提交列表失败" unless @gitea_data.is_a?(Hash)
  end

  def load_gitea_repo_detail
    @gitea_repo_detail = $gitea_client.get_repos_by_owner_repo(owner, repo, {query: {access_token: token}})
    raise Error, "获取项目详情失败" unless @gitea_repo_detail.is_a?(Hash)
  end
end