module Ecs::EcYearsHelper
  def achieved_graduation_course_count(ec_year)
    return 0 if ec_year.ec_courses.count.zero?

    course_ids = ec_year.ec_courses.map(&:id)
    target_count_map = EcCourseTarget.where(ec_course_id: course_ids).group(:ec_course_id).count

    ec_year.ec_courses.sum { |course| course.complete_target_count == target_count_map[course.id] ? 1 : 0 }
  end

  def achieved_graduation_objective_count(ec_year)
    return 0 if ec_year.ec_graduation_subitems.count.zero?

    subitem_ids = ec_year.ec_graduation_subitems.reorder(nil).pluck(:id)

    relations = EcGraduationRequirementCalculation.joins(:ec_course_support).where(ec_course_supports: { ec_graduation_subitem_id: subitem_ids })

    reached_map = relations.where(status: true).group('ec_graduation_subitem_id').count

    reached_map.keys.size
  end
end