class EdFi::Indiana::V2026::StudentGraduationPlanService <
  EdFi::Indiana::V2026::ApplicationService
  def call
    students.each do |student|
      student.student.ed_fi_graduation_plans.each do |graduation_plan|
        create_or_update(graduation_plan, props(graduation_plan))
      end
    end
  end

  def endpoint
    'idoe/studentschoolgraduationplans'
  end

  private
    def students
      @students ||= school_year.school_year_students
        .preload(student: [:ed_fi_graduation_plans, :state_number])
        .joins(:student)
        .where(exit_date: [nil, '', 0])
        .where.not(Students: { GradYear: [nil, '', 0] })
        .distinct
    end

    def props(graduation_plan)
      student = graduation_plan.student
      obj = {
        beginDate: graduation_plan.start_date,
        graduationPlanReference: {
          educationOrganizationId: 1088000000,
          graduationPlanTypeDescriptor:
            "uri://doe.in.gov/GraduationPlanTypeDescriptor##{graduation_plan.plan_descriptor}",
          graduationSchoolYear: student.graduation_year,
        },
        schoolReference: {
          schoolId: state_id.number,
        },
        studentReference: {
          studentUniqueId: student.state_number&.number,
        },
        endDate: graduation_plan.end_date,
      }

      if graduation_plan.alternative_plan_descriptor?
        obj.merge(
          alternativeGraduationPlans: [
            {
              alternativeGraduationPlanReference: {
                educationOrganizationId: 1088000000,
                graduationPlanTypeDescriptor:
                  "uri://doe.in.gov/GraduationPlanTypeDescriptor##{graduation_plan.alternative_plan_descriptor}",
                graduationSchoolYear: student.graduation_year,
              }
            }
          ]
        )
      else
        obj
      end
    end
end
