UPDATE appointment_units
SET requirement_key = COALESCE(
    (
        SELECT r.requirement_key
        FROM appointments a
        JOIN students s ON s.id = a.student_id
        JOIN license_class_templates t ON t.id = s.template_id
        JOIN license_template_requirements r ON r.template_id = t.id
        WHERE a.id = appointment_units.appointment_id
          AND t.is_combination = 1
          AND COALESCE(r.phase_label, '') <> ''
          AND substr(r.requirement_key, instr(r.requirement_key, '::') + 2) = appointment_units.requirement_key
        ORDER BY r.sort_order
        LIMIT 1
    ),
    requirement_key
)
WHERE requirement_key NOT LIKE '%::%'
  AND appointment_id IN (
      SELECT a.id
      FROM appointments a
      JOIN students s ON s.id = a.student_id
      JOIN license_class_templates t ON t.id = s.template_id
      WHERE t.is_combination = 1
  );

DELETE FROM student_requirement_snapshots
WHERE requirement_key NOT LIKE '%::%'
  AND student_id IN (
      SELECT s.id
      FROM students s
      JOIN license_class_templates t ON t.id = s.template_id
      WHERE t.is_combination = 1
  )
  AND EXISTS (
      SELECT 1
      FROM students s
      JOIN license_template_requirements r ON r.template_id = s.template_id
      WHERE s.id = student_requirement_snapshots.student_id
        AND COALESCE(r.phase_label, '') <> ''
        AND substr(r.requirement_key, instr(r.requirement_key, '::') + 2) = student_requirement_snapshots.requirement_key
  );
