ALTER TABLE tuleap_credentials RENAME TO tuleap_credentials_legacy;

CREATE TABLE tuleap_credentials (
    id TEXT PRIMARY KEY,
    project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
    tuleap_url TEXT NOT NULL,
    username TEXT NOT NULL,
    password_encrypted TEXT NOT NULL,
    created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
);

INSERT INTO tuleap_credentials (id, project_id, tuleap_url, username, password_encrypted, created_at)
SELECT id, NULL, tuleap_url, username, password_encrypted, strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
FROM tuleap_credentials_legacy;

DROP TABLE tuleap_credentials_legacy;

CREATE UNIQUE INDEX IF NOT EXISTS idx_tuleap_credentials_project_unique
ON tuleap_credentials(project_id)
WHERE project_id IS NOT NULL;

CREATE UNIQUE INDEX IF NOT EXISTS idx_tuleap_credentials_global_unique
ON tuleap_credentials((project_id IS NULL))
WHERE project_id IS NULL;
