-- +goose Up
-- 统一初始迁移：providers、models、usage_stats 完整表结构
-- models 表使用 UUID 主键 + UNIQUE(provider_id, model_name) 联合唯一约束

CREATE TABLE IF NOT EXISTS providers (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    api_key TEXT NOT NULL,
    base_url TEXT NOT NULL,
    protocol TEXT DEFAULT 'openai',
    enabled INTEGER DEFAULT 1,
    created_at DATETIME,
    updated_at DATETIME
);

CREATE TABLE IF NOT EXISTS models (
    id TEXT PRIMARY KEY,
    provider_id TEXT NOT NULL,
    model_name TEXT NOT NULL,
    enabled INTEGER DEFAULT 1,
    created_at DATETIME,
    FOREIGN KEY (provider_id) REFERENCES providers(id) ON DELETE CASCADE,
    UNIQUE(provider_id, model_name)
);

CREATE TABLE IF NOT EXISTS usage_stats (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    provider_id TEXT NOT NULL,
    model_name TEXT NOT NULL,
    request_count INTEGER DEFAULT 0,
    date DATE NOT NULL,
    UNIQUE(provider_id, model_name, date)
);

CREATE INDEX IF NOT EXISTS idx_models_provider_id ON models(provider_id);
CREATE INDEX IF NOT EXISTS idx_models_model_name ON models(model_name);
CREATE INDEX IF NOT EXISTS idx_usage_stats_provider_model_date ON usage_stats(provider_id, model_name, date);

-- +goose Down
DROP INDEX IF EXISTS idx_usage_stats_provider_model_date;
DROP INDEX IF EXISTS idx_models_model_name;
DROP INDEX IF EXISTS idx_models_provider_id;
DROP TABLE IF EXISTS usage_stats;
DROP TABLE IF EXISTS models;
DROP TABLE IF EXISTS providers;
