class Api::V1::Prime::Eth2Staking::ValidatorsController < Api::V1::Prime::Eth2Staking::BaseController
  def index
    jsonapi_paginate(scope) do |page|
      render jsonapi: page, params: jsonapi_serializer_params.merge(jsonapi_include_params(page))
    end
  end

  def show
    render jsonapi: scope.first!, params: jsonapi_serializer_params.merge(jsonapi_include_params(scope))
  end

  private

  def scope
    scope = current_user.prime_eth2_staking_validators.order(id: :asc)
    scope = scope.where(staking_position_id: params[:position_id]) if params[:position_id]
    scope = scope.includes(:position) if jsonapi_include.include?('position')
    scope = scope.where(id: params[:id]) if params[:id]
    scope
  end

  def jsonapi_include_params(resources)
    {}.tap do |jsonapi_params|
      if params[:status_history]
        jsonapi_params[:status_history] = Prime::Eth2Staking::FetchValidatorStatuses.new(resources).fetch.tap do |statuses_history|
          Prime::Eth2Staking::UpdateCurrentValidatorStatus.new(resources, statuses_history).update
        end
      end
    end
  end

  def jsonapi_include
    super & %w[position]
  end

  # make sure max per page is 100 due to indexer api limitations
  def jsonapi_page_size(pagination_params)
    per_page = pagination_params[:size].to_f.to_i
    per_page = 100 if per_page > 100 || per_page < 1
    per_page
  end
end
