-- Phase-7 public access layer
-- Access policy + allowlist tables for gateway entitlements/rate-limits.

CREATE TABLE IF NOT EXISTS agent_access_policies (
    agent_id TEXT PRIMARY KEY,
    enabled BOOLEAN NOT NULL DEFAULT TRUE,
    public_active BOOLEAN NOT NULL DEFAULT TRUE,
    requires_whitelist BOOLEAN NOT NULL DEFAULT FALSE,
    user_global_limit INTEGER NOT NULL DEFAULT 60,
    user_global_window_seconds INTEGER NOT NULL DEFAULT 300,
    user_agent_limit INTEGER NOT NULL DEFAULT 20,
    user_agent_window_seconds INTEGER NOT NULL DEFAULT 300,
    group_agent_limit INTEGER NOT NULL DEFAULT 10,
    group_agent_window_seconds INTEGER NOT NULL DEFAULT 300,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS agent_allowlist (
    id BIGSERIAL PRIMARY KEY,
    platform TEXT NOT NULL,
    platform_user_id TEXT NOT NULL,
    agent_id TEXT NOT NULL REFERENCES agent_access_policies(agent_id) ON DELETE CASCADE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (platform, platform_user_id, agent_id)
);

CREATE INDEX IF NOT EXISTS idx_agent_access_policies_enabled
    ON agent_access_policies (enabled, public_active);

CREATE INDEX IF NOT EXISTS idx_agent_allowlist_lookup
    ON agent_allowlist (platform, platform_user_id, agent_id);

INSERT INTO agent_access_policies (
    agent_id,
    enabled,
    public_active,
    requires_whitelist
)
VALUES
    ('daarwizz', TRUE, TRUE, FALSE),
    ('helion', TRUE, TRUE, FALSE),
    ('greenfood', TRUE, TRUE, FALSE),
    ('agromatrix', TRUE, TRUE, FALSE),
    ('alateya', TRUE, TRUE, FALSE),
    ('nutra', TRUE, TRUE, FALSE),
    ('druid', TRUE, TRUE, FALSE),
    ('clan', TRUE, TRUE, FALSE),
    ('eonarch', TRUE, TRUE, FALSE),
    ('senpai', TRUE, TRUE, FALSE),
    ('oneok', TRUE, TRUE, FALSE),
    ('soul', TRUE, TRUE, FALSE),
    ('yaromir', TRUE, TRUE, FALSE),
    ('sofiia', TRUE, TRUE, FALSE),
    ('monitor', FALSE, FALSE, TRUE),
    ('aistalk', FALSE, FALSE, TRUE)
ON CONFLICT (agent_id) DO UPDATE
SET
    enabled = EXCLUDED.enabled,
    public_active = EXCLUDED.public_active,
    requires_whitelist = EXCLUDED.requires_whitelist,
    updated_at = now();
