-- Tables affected: qt_configurations
-- recovery.not-started: safe to re-run; ADD COLUMN IF NOT EXISTS
-- recovery.partial: ALTER TABLE qt_configurations DROP COLUMN line_no;
-- recovery.completed: no action needed
-- verify: line_no column missing | SELECT 1 FROM information_schema.COLUMNS WHERE table_schema=DATABASE() AND table_name='qt_configurations' AND column_name='line_no' HAVING COUNT(*)=0

ALTER TABLE qt_configurations
    ADD COLUMN IF NOT EXISTS line_no INT NULL AFTER only_in_stock;

UPDATE qt_configurations q
JOIN (
    SELECT
        id,
        ROW_NUMBER() OVER (
            PARTITION BY COALESCE(NULLIF(TRIM(project_uuid), ''), '__NO_PROJECT__')
            ORDER BY created_at ASC, id ASC
        ) AS rn
    FROM qt_configurations
    WHERE line_no IS NULL OR line_no <= 0
) ranked ON ranked.id = q.id
SET q.line_no = ranked.rn * 10;

ALTER TABLE qt_configurations
    ADD INDEX IF NOT EXISTS idx_qt_configurations_project_line_no (project_uuid, line_no);
