-- Migration 024: Add delegation_chains table for A2A authorization (Phase 5 WS2)
-- Creates the delegation_chains table that stores A2A delegation tokens and their
-- verification signatures, enabling agent-to-agent authority delegation.

CREATE TABLE delegation_chains (
    id                  UUID        PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id           VARCHAR(40) NOT NULL,
    delegator_agent_id  UUID        NOT NULL REFERENCES agents(agent_id) ON DELETE CASCADE,
    delegatee_agent_id  UUID        NOT NULL REFERENCES agents(agent_id) ON DELETE CASCADE,
    scopes              TEXT[]      NOT NULL,
    delegation_token    TEXT        NOT NULL UNIQUE,
    signature           TEXT        NOT NULL,
    ttl_seconds         INTEGER     NOT NULL CHECK (ttl_seconds BETWEEN 60 AND 86400),
    issued_at           TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    expires_at          TIMESTAMPTZ NOT NULL,
    revoked_at          TIMESTAMPTZ,
    created_at          TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Index for token lookup (verify-delegation hot path)
CREATE UNIQUE INDEX idx_delegation_chains_token ON delegation_chains(delegation_token);

-- Index for listing delegations by delegator agent
CREATE INDEX idx_delegation_chains_delegator ON delegation_chains(delegator_agent_id, tenant_id);

-- Index for listing delegations by delegatee agent
CREATE INDEX idx_delegation_chains_delegatee ON delegation_chains(delegatee_agent_id, tenant_id);

-- Index for cleanup of expired chains
CREATE INDEX idx_delegation_chains_expires_at ON delegation_chains(expires_at);
