const { spawn } = require("child_process");
const path = require("path");
const fs = require("fs/promises");

const cwd = __dirname;
const dbPath = path.join(cwd, "data", "db.json");
const baseUrl = "http://127.0.0.1:8787";

async function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function waitForHealth(retries = 20) {
  for (let i = 0; i < retries; i += 1) {
    try {
      const response = await fetch(`${baseUrl}/health`);
      if (response.ok) return;
    } catch {
    }
    await wait(200);
  }
  throw new Error("Server did not become healthy");
}

async function request(pathname, options = {}) {
  const response = await fetch(`${baseUrl}${pathname}`, {
    ...options,
    headers: {
      "Content-Type": "application/json",
      ...(options.headers || {})
    }
  });
  const json = await response.json();
  if (!response.ok) {
    throw new Error(json.error || `Request failed: ${response.status}`);
  }
  return json;
}

async function main() {
  await fs.rm(path.join(cwd, "data"), { recursive: true, force: true });

  const child = spawn(process.execPath, ["server.js"], {
    cwd,
    stdio: "inherit"
  });

  try {
    await waitForHealth();

    const register = await request("/api/v1/auth/register", {
      method: "POST",
      body: JSON.stringify({
        hospital_code: "testuro",
        hospital_name: "测试医院泌尿外科",
        username: "doctor1",
        display_name: "张医生",
        password: "123456"
      })
    });

    const token = register.token;
    const create = await request("/api/v1/followups", {
      method: "POST",
      headers: { Authorization: `Bearer ${token}` },
      body: JSON.stringify({
        admission_number: "ZY001",
        patient_name: "张三",
        disease_type: "结石术后复查",
        procedure_type: "结石术后门诊复查",
        reminder_date: "2026-03-20",
        notes: "测试"
      })
    });

    const list = await request("/api/v1/followups", {
      headers: { Authorization: `Bearer ${token}` }
    });

    await request(`/api/v1/followups/${create.item.id}/complete`, {
      method: "POST",
      headers: { Authorization: `Bearer ${token}` },
      body: JSON.stringify({
        completion_outcome: "已门诊复诊"
      })
    });

    const summary = await request("/api/v1/followups/summary", {
      headers: { Authorization: `Bearer ${token}` }
    });

    console.log("Self-test passed.");
    console.log({
      registeredDoctor: register.doctor.display_name,
      listTotal: list.total,
      summary
    });
  } finally {
    child.kill("SIGTERM");
    await wait(300);
    await fs.readFile(dbPath, "utf8");
  }
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
