class EdFi::Indiana::V2026::CourseSectionStudentCleanupService <
  EdFi::Indiana::V2026::ApplicationService
  def call
    dex_records.each { |r| check_record(r) }
  end

  def endpoint
    'ed-fi/studentsectionassociations'
  end

  def destroy_logs
    nil
  end

  private
    def ed_fi_classes_by_code
      @ed_fi_classes_by_code ||= school.classrooms
        .preload(:school_state_classroom)
        .by_type(['period_long'])
        .where.not(course_number: ['', ' '])
        .index_by(&:course_number)
    end

    def class_subjects_by_id
      @class_subjects_by_id ||= school.class_subjects
        .preload(classroom: :school_state_classroom)
        .where("Classes.type = '1' OR Classes.type = '-1'")
        .index_by(&:id)
    end

    def empty_string_array
      @empty_string_array ||= ['', ' ']
    end

    def dex_records
      @dex_records ||= JSON.parse(rest_client_request(:get, url, nil))
    end

    def ids
      @ids ||= school_year.ed_fi_ids
        .where(endpoint: endpoint)
        .index_by(&:number)
    end

    def check_record(item)
      # check if edfi record has a classroom that is no longer state reporting
      # or if a class subject no longer has a code
      # If either of those are true, delete the record and id.
      code = item['sectionReference']['localCourseCode']
      section_id = item['sectionReference']['sectionIdentifier'].to_i
      id = item['id']
      classroom = ed_fi_classes_by_code[code]
      subject = class_subjects_by_id[section_id]
      if classroom.nil?
        if subject.nil?
          delete(id)
        elsif subject.classroom.school_state_classroom.nil? ||
            empty_string_array.include?(subject.code)
          delete(id)
        end
      elsif classroom.school_state_classroom.nil?
        delete(id)
      end
    end

    def delete(id)
      edfi_id = ids[id]
      if edfi_id.present?
        response = rest_client_request(:delete, "#{url}/#{id}", nil)
        edfi_id.delete unless response.nil?
      else
        rest_client_request(:delete, "#{url}/#{id}", nil)
      end
    end
end
