import test from 'node:test';
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';

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

const jsonFetch = async (
  baseUrl: string,
  path: string,
  options?: { method?: string; body?: unknown },
) => {
  const res = await fetch(`${baseUrl}${path}`, {
    method: options?.method ?? 'GET',
    headers: options?.body ? { 'Content-Type': 'application/json' } : undefined,
    body: options?.body ? JSON.stringify(options.body) : undefined,
  });

  const text = await res.text();
  let json: any = null;
  try {
    json = text ? JSON.parse(text) : null;
  } catch {
    json = null;
  }
  return { status: res.status, json, text };
};

test('用户答题记录接口应返回subjectName（任务记录可从任务反推科目）', async () => {
  const { initDatabase, run } = await import('../api/database');
  await initDatabase();

  const { app } = await import('../api/server');
  const server = app.listen(0);

  try {
    const addr = server.address();
    assert.ok(addr && typeof addr === 'object');
    const baseUrl = `http://127.0.0.1:${addr.port}`;

    const userId = randomUUID();
    const subjectId = randomUUID();
    const taskId = randomUUID();
    const recordId = randomUUID();

    await run(`INSERT INTO users (id, name, phone, password) VALUES (?, ?, ?, ?)`, [
      userId,
      '测试用户',
      '13800138111',
      '',
    ]);

    await run(
      `INSERT INTO exam_subjects (id, name, type_ratios, category_ratios, total_score, duration_minutes)
       VALUES (?, ?, ?, ?, ?, ?)`,
      [
        subjectId,
        '测试科目-任务关联',
        JSON.stringify({ single: 100 }),
        JSON.stringify({ 通用: 100 }),
        100,
        60,
      ],
    );

    const now = new Date().toISOString();
    await run(
      `INSERT INTO exam_tasks (id, name, subject_id, start_at, end_at, selection_config)
       VALUES (?, ?, ?, ?, ?, ?)`,
      [taskId, '测试任务', subjectId, now, now, null],
    );

    // 模拟旧数据：quiz_records.subject_id 为空，仅有 task_id
    await run(
      `INSERT INTO quiz_records (id, user_id, subject_id, task_id, total_score, correct_count, total_count, created_at, score_percentage, status)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [recordId, userId, null, taskId, 80, 16, 20, now, 80, '优秀'],
    );

    const res = await jsonFetch(baseUrl, `/api/quiz/records/${userId}`);
    assert.equal(res.status, 200);
    assert.equal(res.json?.success, true);
    assert.ok(Array.isArray(res.json?.data));

    const row = (res.json?.data as any[]).find((r) => r.id === recordId);
    assert.ok(row);
    assert.equal(row.taskName, '测试任务');
    assert.equal(row.subjectName, '测试科目-任务关联');
  } finally {
    server.close();
  }
});
