-- V008: ai_agent_usage_logs
-- AI 에이전트 사용량 로그 테이블 (토큰/비용 추적)

CREATE TABLE ai_agent_usage_logs (
    id                BIGSERIAL PRIMARY KEY,
    user_id           VARCHAR(64),
    api_key_id        BIGINT REFERENCES ai_agent_api_keys(id) ON DELETE SET NULL,
    agent_id          BIGINT REFERENCES ai_agents(id) ON DELETE SET NULL,
    conversation_id   BIGINT REFERENCES ai_agent_conversations(id) ON DELETE SET NULL,
    provider_name     VARCHAR(50),
    model_name        VARCHAR(100),
    prompt_tokens     INTEGER NOT NULL DEFAULT 0,
    completion_tokens INTEGER NOT NULL DEFAULT 0,
    total_tokens      INTEGER NOT NULL DEFAULT 0,
    cost_usd          NUMERIC(12,6) NOT NULL DEFAULT 0,
    response_time_ms  INTEGER,
    success           BOOLEAN NOT NULL DEFAULT TRUE,
    error_message     TEXT,
    request_path      VARCHAR(500),
    ip_address        INET,
    company_code      VARCHAR(20),
    created_at        TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_usage_created ON ai_agent_usage_logs (created_at DESC);
CREATE INDEX idx_usage_apikey  ON ai_agent_usage_logs (api_key_id, created_at DESC);
CREATE INDEX idx_usage_agent   ON ai_agent_usage_logs (agent_id, created_at DESC);
CREATE INDEX idx_usage_company ON ai_agent_usage_logs (company_code, created_at DESC);
