class Admin::Administration::SchoolYearsController < Admin::Administration::Controller
  def index
    render_success :ok, json: years.map { |p| year_props(p) }
  end

  def show
    render_success :ok, json: year_props(year.decorate)
  end

  def create
    year = years.build(year_params)

    if year.save
      render_success :ok, json: year_props(year)
    else
      render_error :unprocessable_entity, errors: year
    end
  end

  def update
    if year.update(year_params)
      render_success :ok, json: year_props(year)
    else
      render_error :unprocessable_entity, errors: year
    end
  end

  def destroy
    if year.destroy
      render_success :ok
    else
      render_error :unprocessable_entity
    end
  end

  private
    def years
      current_school.school_years
    end

    def year
      @year ||= years.find_by(id: params[:id])
    end

    def school_config
      @school_config ||= current_school.school_config
    end

    def school_days_by_quarter
      @school_days_by_quarter ||= year.school_days.ordered.group_by(&:quarter)
    end

    def year_params
      params.permit(
        :name,
        :description,
        :academic_year,
        :q1_start,
        :q2_start,
        :q3_start,
        :q4_start,
        :end,
        :cycle_days
      )
    end

    def year_props(year)
      {}.tap do |props|
        props[:id] = year.id
        props[:name] = year.name
        props[:description] = year.description
        props[:academic_year] = year.academic_year
        props[:current] = year.current?
        return props if school_config.sessions?

        props[:q1_start] = year.q1_start
        props[:q2_start] = year.q2_start
        props[:q3_start] = year.q3_start if school_config.semesters? || school_config.trimesters?
        props[:q4_start] = year.q4_start if school_config.semesters?
        props[:end] = year.end

        return props unless action_name.to_sym == :show

        props[:cycle_days] = year.cycle_days
        props[:q1_date_range] = year.formatted_date_range(1)
        props[:q2_date_range] = year.formatted_date_range(2)
        props[:q1_days] = school_days_by_quarter[1].count
        props[:q2_days] = school_days_by_quarter[2].count

        if school_config.semesters? || school_config.trimesters?
          props[:q3_date_range] = year.formatted_date_range(3)
          props[:q3_days] = school_days_by_quarter[3].count
        end

        if school_config.semesters?
          props[:q4_date_range] = year.formatted_date_range(4)
          props[:q4_days] = school_days_by_quarter[4].count
        end
      end
    end
end
