CREATE TABLE IF NOT EXISTS permissions_previous (
    id TEXT PRIMARY KEY,
    user_id TEXT NOT NULL,
    resource_type TEXT NOT NULL CHECK(resource_type IN ('global', 'collection', 'document')),
    resource_id TEXT,
    permission TEXT NOT NULL CHECK(permission IN ('read', 'write', 'admin')),
    granted_by TEXT,
    created_at TEXT NOT NULL,
    FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY(granted_by) REFERENCES users(id) ON DELETE SET NULL
);

INSERT INTO permissions_previous (id, user_id, resource_type, resource_id, permission, granted_by, created_at)
SELECT id, user_id, resource_type, resource_id, permission, granted_by, created_at
FROM permissions
WHERE resource_type IN ('global', 'collection', 'document');

DROP TABLE permissions;
ALTER TABLE permissions_previous RENAME TO permissions;

CREATE INDEX IF NOT EXISTS idx_permissions_user ON permissions(user_id);
