class OneRoster::UsersController < OneRoster::Controller
  include OneRoster::UserScoped

  before_action :authorize_roster_scope
  before_action :validate_school_id, only: :index
  after_action :set_total_count_header, only: :index

  def index
    render_success :ok, json: {
      users: bind_and_parse(users.map { |u| user_props(u, current_ids) })
    }
  end

  def show
    if student_or_user
      current_id = [student_or_user.current_school_year_student&.student_id]
      render_success :ok, json: { user: user_props(student_or_user, current_id) }
    else
      render_error :not_found
    end
  end

  private
    def student_or_user
      @student_or_user ||= current_school.send(model).find_by(id: id)
    end

    def employees
      @employees ||= current_school.employees.teachers_and_superusers.distinct
    end

    def students
      @students ||= current_school.students
        .includes(:user)
        .by_school_year(current_school_year.id)
        .joins(:user)
    end

    def users
      @users ||= students + employees
    end

    def current_ids
      @current_ids ||= students.current_status(current_school, :current).pluck(:id)
    end

    def set_total_count_header
      response.set_header('X-Total-Count', users.count.to_s)
    end
end
