class Support::Sites::SchoolDistrictController < Support::Sites::Controller
  def index
    render_success :ok, json: schools_without_district.map { |school| district_props(school) }
  end

  def show
    render_success :ok, json: district_schools.map { |school| district_props(school) }
  end

  def attach
    success = School.transaction do
      school_district.schools << school
      school.catholic_school = true if district_school.catholic_diocese_office?

      school.save!
    end
    if success
      render_success :ok, json: district_props(school)
    else
      render_error :unprocessable_entity
    end
  end

  def detach
    success = school.transaction do
      school.school_district = nil
      school.school_district_school.destroy
      school.school_district_students.destroy_all
      school.school_district_users.destroy_all
      school.catholic_school = false if district_school.catholic_diocese_office?

      school.save!
    end
    if success
      render_success :ok, json: district_props(school)
    else
      render_error :unprocessable_entity
    end
  end

  private
    def schools
      @schools ||= School.order(active: :desc)
    end

    def school
      @school ||= schools.find_by(id: params[:school_id])
    end

    def schools_without_district
      ids = schools.joins(:school_district).ids
      @schools_without_district ||= schools.where.not(id: ids).ordered
    end

    def school_district
      @school_district ||= ::SchoolDistrict.find_by(school_id: params[:district_id])
    end

    def school_district_students
      @school_district_students ||= ::SchoolDistrictStudent.find_by(school_id: school.id)
    end

    def school_district_users
      @school_district_users ||= ::SchoolDistrictUser.find_by(school_id: school.id)
    end

    def district_school
      @district_school ||= ::DistrictSchool.find_by(id: params[:district_id])
    end

    def district_schools
      @district_schools ||= ::SchoolDistrict
        .find_by(school_id: params[:id] || params[:district_id])
        .schools
        .where.not(id: params[:id])
    end

    def district_props(school)
      {
        id: school.id,
        name: school.name,
        active: school.active
      }
    end
end
