-- Phase 5: Agent authentication & RBAC
CREATE TABLE IF NOT EXISTS agents (
    id TEXT PRIMARY KEY DEFAULT 'agent-' || substr(md5(random()::text), 1, 8),
    name TEXT NOT NULL,
    role TEXT NOT NULL DEFAULT 'worker',
    api_key_hash TEXT NOT NULL,
    project_ids TEXT[] DEFAULT '{}',
    created_at TIMESTAMPTZ DEFAULT NOW(),
    last_seen_at TIMESTAMPTZ,
    active BOOLEAN DEFAULT TRUE
);

CREATE INDEX IF NOT EXISTS idx_agents_active ON agents (active);
CREATE INDEX IF NOT EXISTS idx_agents_role ON agents (role);

CREATE TABLE IF NOT EXISTS auth_events (
    id BIGSERIAL PRIMARY KEY,
    agent_id TEXT REFERENCES agents(id),
    action TEXT NOT NULL,
    resource TEXT,
    timestamp TIMESTAMPTZ DEFAULT NOW()
);
