-- Align default seeded courses with program: Beginner→A1,A2; Intermediate→B1,B2; Advanced→C1,C2.
-- Only touches rows with the system seed description; custom courses are unchanged.
-- Removing a course cascades to modules, lessons, and related LMS progress (see FKs on those tables).

DELETE FROM courses AS c
    USING programs AS p
WHERE c.program_id = p.id
  AND c.description = 'Default CEFR level course (system seed).'
  AND (
    (
        p.name = 'Beginner'
        AND c.name IN ('B1', 'B2', 'C1', 'C2')
    )
    OR (
        p.name = 'Intermediate'
        AND c.name IN ('A1', 'A2', 'C1', 'C2')
    )
    OR (
        p.name = 'Advanced'
        AND c.name IN ('A1', 'A2', 'B1', 'B2')
    )
  );

INSERT INTO courses (program_id, name, description, thumbnail)
SELECT
    p.id,
    v.name,
    'Default CEFR level course (system seed).',
    NULL
FROM programs AS p
INNER JOIN (
    VALUES
        ('Beginner', 'A1'),
        ('Beginner', 'A2'),
        ('Intermediate', 'B1'),
        ('Intermediate', 'B2'),
        ('Advanced', 'C1'),
        ('Advanced', 'C2')
) AS v (program_name, name)
    ON p.name = v.program_name
WHERE
    NOT EXISTS (
        SELECT 1 FROM courses AS e
        WHERE e.program_id = p.id AND e.name = v.name
    );
