-- V005: ai_agent_api_keys
-- AI 에이전트 API 키 테이블 (sk-pipe-* 형식)

CREATE TABLE ai_agent_api_keys (
    id                   BIGSERIAL PRIMARY KEY,
    name                 VARCHAR(200) NOT NULL,
    key_hash             CHAR(64) NOT NULL UNIQUE,
    key_prefix           VARCHAR(16) NOT NULL,
    user_id              VARCHAR(64) NOT NULL,
    company_code         VARCHAR(20),
    agent_id             BIGINT REFERENCES ai_agents(id) ON DELETE SET NULL,
    permissions          JSONB NOT NULL DEFAULT '["chat"]'::jsonb,
    rate_limit           INTEGER NOT NULL DEFAULT 60,
    monthly_token_limit  BIGINT NOT NULL DEFAULT 1000000,
    status               VARCHAR(20) NOT NULL DEFAULT 'active'
                         CHECK (status IN ('active','revoked')),
    last_used_at         TIMESTAMPTZ,
    usage_count          BIGINT NOT NULL DEFAULT 0,
    total_tokens         BIGINT NOT NULL DEFAULT 0,
    expires_at           TIMESTAMPTZ,
    created_at           TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_api_keys_hash    ON ai_agent_api_keys (key_hash);
CREATE INDEX idx_api_keys_user    ON ai_agent_api_keys (user_id);
CREATE INDEX idx_api_keys_company ON ai_agent_api_keys (company_code);
CREATE INDEX idx_api_keys_status  ON ai_agent_api_keys (status);
