-- Migration: Add missing columns to chat_messages table
-- Execute this on existing database to add new columns

-- Add token tracking columns
ALTER TABLE chat_messages ADD COLUMN IF NOT EXISTS prompt_tokens INTEGER;
ALTER TABLE chat_messages ADD COLUMN IF NOT EXISTS completion_tokens INTEGER;
ALTER TABLE chat_messages ADD COLUMN IF NOT EXISTS total_tokens INTEGER;

-- Add latency tracking columns
ALTER TABLE chat_messages ADD COLUMN IF NOT EXISTS latency_ms INTEGER;
ALTER TABLE chat_messages ADD COLUMN IF NOT EXISTS first_token_ms INTEGER;

-- Add error tracking columns
ALTER TABLE chat_messages ADD COLUMN IF NOT EXISTS is_error BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE chat_messages ADD COLUMN IF NOT EXISTS error_message VARCHAR;

-- Create API Keys table if not exists
CREATE TABLE IF NOT EXISTS api_keys (
    id UUID NOT NULL PRIMARY KEY,
    key VARCHAR NOT NULL UNIQUE,
    name VARCHAR NOT NULL,
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,
    updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL
);

-- Create API Keys indexes
CREATE INDEX IF NOT EXISTS ix_api_keys_key ON api_keys (key);
CREATE INDEX IF NOT EXISTS ix_api_keys_is_active ON api_keys (is_active);
