-- +goose Up
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    chat_id INTEGER NOT NULL UNIQUE,
    language TEXT NOT NULL DEFAULT 'en',
    created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS user_preferences (
    user_id INTEGER PRIMARY KEY REFERENCES users(id),
    default_media_type TEXT NOT NULL DEFAULT 'video_audio',
    default_quality TEXT NOT NULL DEFAULT 'best',
    default_container TEXT NOT NULL DEFAULT 'mp4',
    default_language TEXT NOT NULL DEFAULT ''
);

CREATE TABLE IF NOT EXISTS user_quotas (
    user_id INTEGER PRIMARY KEY REFERENCES users(id),
    daily_limit_mb INTEGER NOT NULL DEFAULT 100,
    daily_used_mb INTEGER NOT NULL DEFAULT 0,
    daily_date TEXT NOT NULL DEFAULT '',
    weekly_limit_mb INTEGER NOT NULL DEFAULT 500,
    weekly_used_mb INTEGER NOT NULL DEFAULT 0,
    week_start TEXT NOT NULL DEFAULT '',
    monthly_limit_mb INTEGER NOT NULL DEFAULT 2000,
    monthly_used_mb INTEGER NOT NULL DEFAULT 0,
    month_start TEXT NOT NULL DEFAULT '',
    updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS download_history (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL REFERENCES users(id),
    url TEXT NOT NULL,
    title TEXT NOT NULL,
    media_type TEXT NOT NULL,
    format_id TEXT NOT NULL,
    container TEXT NOT NULL,
    file_size INTEGER NOT NULL DEFAULT 0,
    status TEXT NOT NULL DEFAULT 'completed',
    created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_history_user ON download_history(user_id);
CREATE INDEX IF NOT EXISTS idx_history_user_created ON download_history(user_id, created_at);

-- +goose Down
DROP TABLE IF EXISTS download_history;
DROP TABLE IF EXISTS user_quotas;
DROP TABLE IF EXISTS user_preferences;
DROP TABLE IF EXISTS users;
