CREATE TABLE IF NOT EXISTS permissions_next (
    id TEXT PRIMARY KEY,
    user_id TEXT NOT NULL,
    resource_type TEXT NOT NULL CHECK(resource_type IN ('global', 'collection', 'document', 'folder')),
    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_next (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;

DROP TABLE permissions;
ALTER TABLE permissions_next RENAME TO permissions;

CREATE INDEX IF NOT EXISTS idx_permissions_user ON permissions(user_id);
CREATE INDEX IF NOT EXISTS idx_permissions_resource ON permissions(resource_type, resource_id);
