-- Fix theses that were imported with column-shifted CSV data.
-- Orientation names ended up in synopsis, finality names in context_note,
-- and keywords in remarks. Move them to the correct FK columns.

-- 1. Fix orientation_id from synopsis
UPDATE theses SET
    orientation_id = (SELECT o.id FROM orientations o WHERE LOWER(o.name) = LOWER(theses.synopsis)),
    synopsis = NULL
WHERE orientation_id IS NULL
  AND synopsis IS NOT NULL
  AND synopsis != ''
  AND EXISTS (SELECT 1 FROM orientations o WHERE LOWER(o.name) = LOWER(theses.synopsis));

-- 2. Fix finality_id from context_note
UPDATE theses SET
    finality_id = (SELECT ft.id FROM finality_types ft WHERE LOWER(ft.name) = LOWER(theses.context_note)),
    context_note = NULL
WHERE finality_id IS NULL
  AND context_note IS NOT NULL
  AND context_note != ''
  AND EXISTS (SELECT 1 FROM finality_types ft WHERE LOWER(ft.name) = LOWER(theses.context_note));

-- 3. Fix AP program from synopsis (if any synopsis values match AP names — edge case)
UPDATE theses SET
    ap_program_id = (SELECT ap.id FROM ap_programs ap WHERE LOWER(ap.name) = LOWER(theses.synopsis)),
    synopsis = NULL
WHERE ap_program_id IS NULL
  AND synopsis IS NOT NULL
  AND synopsis != ''
  AND EXISTS (SELECT 1 FROM ap_programs ap WHERE LOWER(ap.name) = LOWER(theses.synopsis));
