-- 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);
