class Api::V1::Projects::Actions::Runs::ListService < ApplicationService
  include ActiveModel::Model

  attr_reader :project, :token, :owner, :repo, :workflow, :page, :limit
  attr_accessor :gitea_data 

  validates :workflow, presence: true 

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

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

    @gitea_data
  end

  private 
  def request_params
    {
      access_token: token,
      workflow: workflow,
      page: page,
      limit: limit
    }
  end

  def load_gitea_data
    @gitea_data = $gitea_hat_client.get_repos_actions_by_owner_repo(owner, repo, {query: request_params}) rescue nil 
    raise Error, '获取流水线执行记录失败！' unless @gitea_data.is_a?(Hash)
  end
end