require 'sidekiq-scheduler'

class SchoolSnapshotJob
  include Sidekiq::Worker

  def perform
    schools.each do |school_id|
      SchoolSnapshot.create(
        school_id: school_id,
        academic_year: academic_year,
        employee_count: current_employees[school_id].to_i,
        student_count: current_students[school_id].to_i,
        family_count: current_families[school_id].to_i
      )
    end
  end

  private
    def academic_year
      Time.zone.now.year + 1
    end

    def current_employees
      @current_employees ||= Employee
        .where(current: true, school_id: schools)
        .group(:school_id)
        .count
    end

    def current_students
      @current_students ||= SchoolYearStudent
        .joins(:student)
        .where(current: true, school_id: schools, school_year_id: current_school_year_ids)
        .group(:school_id)
        .count
    end

    def current_families
      @current_families ||= SchoolYearFamily
        .joins(:family)
        .where(school_id: schools, school_year_id: current_school_year_ids)
        .group(:school_id)
        .count
    end

    def schools
      @schools ||= School
        .customer.by_active(true)
        .is_district(false)
        .where(id: current_school_ids)
        .pluck(:id)
    end

    def current_school_ids
      current_school_year_id_by_school_id.values
    end

    def current_school_year_ids
      current_school_year_id_by_school_id.keys
    end

    def current_school_year_id_by_school_id
      current_school_year_id_by_school_id ||= SchoolYear
        .where(current: true, academic_year: academic_year)
        .pluck(:id, :school_id)
        .to_h
    end
end
