-- Tables affected: qt_projects
-- recovery.not-started: check first; idempotent backfill but ADD COLUMN fails if code already exists
-- recovery.partial: ALTER TABLE qt_projects DROP INDEX idx_qt_projects_code; ALTER TABLE qt_projects DROP COLUMN code;
-- recovery.completed: no action needed
-- verify: code column in qt_projects missing | SELECT 1 FROM information_schema.COLUMNS WHERE table_schema=DATABASE() AND table_name='qt_projects' AND column_name='code' HAVING COUNT(*)=0

-- Add project code and enforce uniqueness

ALTER TABLE qt_projects
    ADD COLUMN code VARCHAR(100) NULL AFTER owner_username;

-- Copy code from current project name (truncate to fit)
UPDATE qt_projects
SET code = LEFT(TRIM(COALESCE(name, '')), 100);

-- Fallback for any remaining blanks
UPDATE qt_projects
SET code = uuid
WHERE code IS NULL OR TRIM(code) = '';

-- Drop unique index if it already exists to allow de-duplication updates
DROP INDEX IF EXISTS idx_qt_projects_code ON qt_projects;

-- De-duplicate codes: OPS-1948-2, OPS-1948-3... (MariaDB without CTE)
UPDATE qt_projects p
JOIN (
    SELECT p1.id,
           p1.code AS base_code,
           (
               SELECT COUNT(*)
               FROM qt_projects p2
               WHERE p2.code = p1.code AND p2.id <= p1.id
           ) AS rn
    FROM qt_projects p1
) r ON r.id = p.id
SET p.code = CASE
    WHEN r.rn = 1 THEN r.base_code
    ELSE CONCAT(LEFT(r.base_code, 90), '-', r.rn)
END;

ALTER TABLE qt_projects
    MODIFY COLUMN code VARCHAR(100) NOT NULL;

CREATE UNIQUE INDEX idx_qt_projects_code ON qt_projects(code);
