-- Multi-Tenant Platform Schema
-- Migration: 005_tenants.sql

-- Tenants table - each client/organization
CREATE TABLE tenants (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    api_key TEXT UNIQUE NOT NULL,  -- sk-tenant-xxx
    api_key_hash TEXT NOT NULL,     -- For secure lookup

    -- Configuration
    default_model TEXT NOT NULL DEFAULT 'openai:gpt-4o',
    rate_limit_per_minute INTEGER NOT NULL DEFAULT 60,
    monthly_token_limit INTEGER,  -- NULL = unlimited

    -- Status
    is_active BOOLEAN NOT NULL DEFAULT true,

    -- Metadata
    metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_tenants_api_key_hash ON tenants(api_key_hash);
CREATE INDEX idx_tenants_active ON tenants(is_active) WHERE is_active = true;

-- Agents table - registered agents in the platform
CREATE TABLE agents (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL UNIQUE,  -- 'support', 'research', 'code-review'
    description TEXT,

    -- Agent configuration
    default_model TEXT,  -- Override tenant default if set
    agent_class TEXT NOT NULL,  -- Python class path: 'myapp.agents.support:support_agent'

    -- Metadata
    is_active BOOLEAN NOT NULL DEFAULT true,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Tenant-Agent access mapping
CREATE TABLE tenant_agents (
    tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
    agent_id TEXT NOT NULL REFERENCES agents(id) ON DELETE CASCADE,

    -- Per-tenant-agent configuration overrides
    model_override TEXT,  -- Use different model for this tenant
    custom_instructions TEXT,  -- Append to agent instructions

    -- Access control
    is_default BOOLEAN NOT NULL DEFAULT false,  -- Default agent for this tenant

    PRIMARY KEY (tenant_id, agent_id)
);

CREATE INDEX idx_tenant_agents_tenant ON tenant_agents(tenant_id);

-- API Keys table - support multiple keys per tenant
CREATE TABLE api_keys (
    id TEXT PRIMARY KEY,
    tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
    key_hash TEXT NOT NULL UNIQUE,  -- SHA256 of the key
    key_prefix TEXT NOT NULL,  -- First 8 chars for identification: 'sk-xxxxx'

    name TEXT,  -- Optional label: 'Production', 'Development'

    -- Permissions
    scopes TEXT[] NOT NULL DEFAULT ARRAY['chat'],  -- 'chat', 'admin', 'usage'

    -- Limits (override tenant defaults)
    rate_limit_override INTEGER,

    -- Status
    is_active BOOLEAN NOT NULL DEFAULT true,
    last_used_at TIMESTAMPTZ,
    expires_at TIMESTAMPTZ,

    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_api_keys_hash ON api_keys(key_hash);
CREATE INDEX idx_api_keys_tenant ON api_keys(tenant_id);

-- Update usage_records to include tenant
ALTER TABLE usage_records ADD COLUMN IF NOT EXISTS tenant_id TEXT REFERENCES tenants(id);
CREATE INDEX IF NOT EXISTS idx_usage_tenant ON usage_records(tenant_id, created_at DESC);
