BEGIN;

CREATE TABLE IF NOT EXISTS oauth_clients (
    client_id VARCHAR(64) PRIMARY KEY,
    name VARCHAR(255),
    secret_hash VARCHAR(255) NOT NULL,
    prev_secret_hash VARCHAR(255),
    prev_expires_at TIMESTAMP WITH TIME ZONE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_oauth_clients_updated_at ON oauth_clients(updated_at);

INSERT INTO permissions (code, description, resource, action) VALUES
('iam:client:read', 'List OAuth clients', 'client', 'read'),
('iam:client:write', 'Create/Rotate OAuth clients', 'client', 'write')
ON CONFLICT (code) DO NOTHING;

INSERT INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
JOIN permissions p ON p.code IN ('iam:client:read', 'iam:client:write')
WHERE r.is_system = TRUE
ON CONFLICT DO NOTHING;

COMMIT;

