-- ============================================================
-- Classroom Copilot — Phase C Migration
-- 003: Clean schema + lesson planning tables
-- Run after: 002_schema.sql
-- ============================================================

-- ============================================================
-- 1. Drop legacy tables (Neo4j-era, replaced by Phase B/C design)
-- ============================================================

DROP TABLE IF EXISTS lesson_whiteboards  CASCADE;
DROP TABLE IF EXISTS timetable_lessons   CASCADE;
DROP TABLE IF EXISTS timetable_classes   CASCADE;
DROP TABLE IF EXISTS timetables          CASCADE;
DROP TABLE IF EXISTS lessons             CASCADE;
DROP TABLE IF EXISTS audit_logs         CASCADE;
DROP TABLE IF EXISTS function_logs      CASCADE;

-- ============================================================
-- 2. planned_lessons — drop Neo4j-era field, add course support
-- ============================================================

-- Drop stale Neo4j reference field and its index
DROP INDEX   IF EXISTS idx_pl_timetable_period;
ALTER TABLE  planned_lessons DROP COLUMN IF EXISTS timetable_period_id;

-- Course support (nullable — populated when courses feature ships)
ALTER TABLE planned_lessons
    ADD COLUMN IF NOT EXISTS course_id        UUID,
    ADD COLUMN IF NOT EXISTS sequence_number  INTEGER;

CREATE INDEX IF NOT EXISTS idx_pl_course ON planned_lessons(course_id) WHERE course_id IS NOT NULL;

-- ============================================================
-- 3. lesson_deliveries — link to taught_lessons
-- ============================================================

ALTER TABLE lesson_deliveries
    ADD COLUMN IF NOT EXISTS taught_lesson_id UUID
        REFERENCES taught_lessons(id) ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS idx_ld_taught_lesson ON lesson_deliveries(taught_lesson_id)
    WHERE taught_lesson_id IS NOT NULL;

-- ============================================================
-- 4. Verify Phase C tables exist (idempotent — safe to re-run)
-- These are defined in 002_schema.sql; IF NOT EXISTS means
-- running 002 first is sufficient, but listed here for clarity.
-- ============================================================

-- planned_lessons, lesson_collaborators, lesson_deliveries
-- curriculum_topics
-- All present in 002_schema.sql — no action needed here.
