-- Add projects and attach configurations to projects

CREATE TABLE qt_projects (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    uuid CHAR(36) NOT NULL UNIQUE,
    owner_username VARCHAR(100) NOT NULL,
    name VARCHAR(200) NOT NULL,
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    is_system BOOLEAN NOT NULL DEFAULT FALSE,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_qt_projects_owner_username (owner_username),
    INDEX idx_qt_projects_is_active (is_active),
    INDEX idx_qt_projects_is_system (is_system)
);

ALTER TABLE qt_configurations
    ADD COLUMN project_uuid CHAR(36) NULL AFTER app_version,
    ADD INDEX idx_qt_configurations_project_uuid (project_uuid),
    ADD CONSTRAINT fk_qt_configurations_project_uuid
        FOREIGN KEY (project_uuid) REFERENCES qt_projects(uuid)
        ON UPDATE CASCADE
        ON DELETE SET NULL;

-- One system project per owner: "Без проекта"
INSERT INTO qt_projects (uuid, owner_username, name, is_active, is_system, created_at, updated_at)
SELECT UUID(), owners.owner_username, 'Без проекта', TRUE, TRUE, NOW(), NOW()
FROM (
    SELECT DISTINCT owner_username
    FROM qt_configurations
) AS owners
LEFT JOIN qt_projects p
    ON p.owner_username = owners.owner_username
   AND p.name = 'Без проекта'
   AND p.is_system = TRUE
WHERE p.id IS NULL;

-- Attach all existing configurations without project to the system project
UPDATE qt_configurations c
JOIN qt_projects p
    ON p.owner_username = c.owner_username
   AND p.name = 'Без проекта'
   AND p.is_system = TRUE
SET c.project_uuid = p.uuid
WHERE c.project_uuid IS NULL OR c.project_uuid = '';
