-- One-time migration: move scad_deadlines.category into dedicated scad_subjects table

CREATE TABLE IF NOT EXISTS scad_subjects (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    color VARCHAR(7) NOT NULL DEFAULT '#6c757d',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uniq_name (name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT IGNORE INTO scad_subjects (name)
SELECT DISTINCT TRIM(category) FROM scad_deadlines
WHERE category IS NOT NULL AND TRIM(category) <> '';

ALTER TABLE scad_deadlines
    ADD COLUMN subject_id INT UNSIGNED NULL AFTER id,
    ADD INDEX idx_subject (subject_id),
    ADD CONSTRAINT fk_deadlines_subject FOREIGN KEY (subject_id) REFERENCES scad_subjects(id) ON DELETE SET NULL;

UPDATE scad_deadlines d
JOIN scad_subjects s ON s.name = TRIM(d.category)
SET d.subject_id = s.id;

ALTER TABLE scad_deadlines DROP COLUMN category;
