// ============================================================
// infrastructure/storage/schema.ts — 数据库 Schema 定义
// ============================================================

/** 当前 schema 版本 */
export const SCHEMA_VERSION = 1;

/** 建表 DDL（所有 CREATE TABLE IF NOT EXISTS） */
export const DDL_STATEMENTS = [
  // ---- 任务记录 ----
  `CREATE TABLE IF NOT EXISTS task_records (
    id         TEXT PRIMARY KEY,
    user_id    TEXT NOT NULL,
    model_id   TEXT NOT NULL,
    status     TEXT NOT NULL,
    data_json  TEXT NOT NULL,
    created_at INTEGER NOT NULL,
    updated_at INTEGER NOT NULL
  )`,
  `CREATE INDEX IF NOT EXISTS idx_task_user_status ON task_records(user_id, status)`,
  `CREATE INDEX IF NOT EXISTS idx_task_user_model  ON task_records(user_id, model_id)`,

  // ---- 订单记录 ----
  `CREATE TABLE IF NOT EXISTS order_records (
    id         TEXT PRIMARY KEY,
    user_id    TEXT NOT NULL,
    order_type TEXT NOT NULL,
    status     TEXT NOT NULL,
    data_json  TEXT NOT NULL,
    created_at INTEGER NOT NULL
  )`,
  `CREATE INDEX IF NOT EXISTS idx_order_user_type ON order_records(user_id, order_type)`,

  // ---- 参数历史 ----
  `CREATE TABLE IF NOT EXISTS param_history (
    id                INTEGER PRIMARY KEY AUTOINCREMENT,
    task_id           TEXT UNIQUE NOT NULL,
    user_id           TEXT NOT NULL,
    model_id          TEXT NOT NULL,
    model_name        TEXT NOT NULL,
    input_params_json TEXT NOT NULL,
    output_data_json  TEXT,
    tag               TEXT,
    created_at        INTEGER NOT NULL
  )`,
  `CREATE INDEX IF NOT EXISTS idx_param_user_model ON param_history(user_id, model_id, created_at)`,

  // ---- 媒体缓存 ----
  `CREATE TABLE IF NOT EXISTS media_cache (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id      TEXT NOT NULL,
    url_hash     TEXT UNIQUE NOT NULL,
    original_url TEXT NOT NULL,
    local_path   TEXT NOT NULL,
    mime_type    TEXT NOT NULL,
    file_size    INTEGER NOT NULL,
    created_date TEXT NOT NULL,
    accessed_at  INTEGER NOT NULL
  )`,
  `CREATE INDEX IF NOT EXISTS idx_media_user_hash ON media_cache(user_id, url_hash)`,

  // ---- 同步游标 ----
  `CREATE TABLE IF NOT EXISTS sync_cursor (
    data_type   TEXT PRIMARY KEY,
    last_page   INTEGER NOT NULL,
    total_count INTEGER NOT NULL,
    synced_at   INTEGER NOT NULL
  )`,

  // ---- 应用设置 ----
  `CREATE TABLE IF NOT EXISTS app_settings (
    key        TEXT PRIMARY KEY,
    value      TEXT NOT NULL,
    updated_at INTEGER NOT NULL
  )`,

  // ---- Schema 版本 ----
  `CREATE TABLE IF NOT EXISTS _schema_version (version INTEGER PRIMARY KEY)`,
];

/** 初始化 schema 版本记录 */
export const INIT_VERSION_SQL = `INSERT OR IGNORE INTO _schema_version (version) VALUES (${SCHEMA_VERSION})`;
