class Employee::Legacy::Classrooms::AttendancesController < Employee::Controller
  include Employee::ClassroomScoped

  def show
    return render_error :not_found, errors: 'Not a school day' unless school_day

    data = {
      date: params[:date].to_date,
      quarter: school_year.closest_quarter(params[:date]),
      students: students.map { |s| student_attendance_props(s) }
    }
    render_success :ok, json: data
  end

  def create
    attendance = student.attendances
      .find_or_initialize_by(classroom: classroom, date: params[:date])
    attendance.assign_attributes(attendance_params)
    attendance.type = type if type

    if attendance.save
      render_success :ok, message: 'Attendance saved'
    else
      render_error :unprocessable_entity, errors: attendance
    end
  end

  def batch_create
    records = students.where(id: params[:student_ids]).map do |student|
      record = student.attendances
        .find_or_initialize_by(classroom: classroom, date: params[:date])
      record.is_present = params[:is_present]
      record
    end

    if transactional_save(records)
      render_success :ok, message: 'Attendances created'
    else
      render_error :unprocessable_entity, message: 'Something went wrong'
    end
  end

  private
    def students
      classroom.students
    end

    def student
      @student ||= students.find_by(id: params[:student_id])
    end

    def student_attendance
      @student_attendance ||= classroom.attendances
        .where(date: params[:date])
        .index_by(&:student_id)
    end

    def school_year
      current_school.school_years.current
    end

    def school_day
      school_year.school_days.find_by(date: params[:date])
    end

    def type
      @type ||= current_school.attendance_types.find_by(id: params[:type_id])
    end

    def attendance_params
      params.permit(:date, :is_present, :tardy, :excused, :unexcused)
    end

    def student_attendance_props(student)
      attendance = student_attendance[student.id]

      {}.tap do |props|
        props[:student_id] = student.id
        props[:full_name] = student.full_name(:reverse)
      end.merge(attendance_results(attendance))
    end

    def attendance_results(attendance)
      {
        is_present: attendance&.is_present?,
        tardy: attendance&.tardy? || false,
        excused: attendance&.excused? || false,
        unexcused: attendance&.unexcused? || false,
        type_id: attendance&.type_id&.zero? ? nil : attendance&.type_id
      }
    end
end
