import test from 'node:test';
import assert from 'node:assert/strict';

process.env.NODE_ENV = 'test';
process.env.DB_PATH = ':memory:';

test('历史数据库 questions.score > 0 约束应迁移为 >= 0', async () => {
  const { initDbConnection, initDatabase, run } = await import('../api/database');

  // 手工创建“旧版本”最小可启动 schema：让 initDatabase 走“表已存在”分支
  await initDbConnection();

  await run(`
    CREATE TABLE users (
      id TEXT PRIMARY KEY,
      name TEXT NOT NULL,
      phone TEXT UNIQUE NOT NULL,
      password TEXT NOT NULL DEFAULT '',
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    );
  `);

  await run(`
    CREATE TABLE questions (
      id TEXT PRIMARY KEY,
      content TEXT NOT NULL,
      type TEXT NOT NULL,
      options TEXT,
      answer TEXT NOT NULL,
      score INTEGER NOT NULL CHECK(score > 0),
      category TEXT NOT NULL DEFAULT '通用',
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    );
  `);

  await run(`
    CREATE TABLE quiz_records (
      id TEXT PRIMARY KEY,
      user_id TEXT NOT NULL,
      subject_id TEXT,
      task_id TEXT,
      total_score INTEGER NOT NULL,
      correct_count INTEGER NOT NULL,
      total_count INTEGER NOT NULL,
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    );
  `);

  await initDatabase();

  // 迁移后应允许插入 score=0
  await assert.doesNotReject(async () => {
    await run(
      `INSERT INTO questions (id, content, type, options, answer, score, category)
       VALUES ('q1', '0分题', 'text', NULL, '', 0, '通用')`,
    );
  });
});
