/**
 * Self-test dashboard hybrid MySQL assembly.
 */
import fs from "fs";
import path from "path";

function loadEnv() {
  const t = fs.readFileSync(path.join(process.cwd(), ".env"), "utf8");
  for (const line of t.split(/\r?\n/)) {
    const s = line.trim();
    if (!s || s.startsWith("#")) continue;
    const eq = s.indexOf("=");
    if (eq <= 0) continue;
    const k = s.slice(0, eq).trim();
    let v = s.slice(eq + 1).trim();
    if (
      (v.startsWith('"') && v.endsWith('"')) ||
      (v.startsWith("'") && v.endsWith("'"))
    )
      v = v.slice(1, -1);
    process.env[k] = v;
  }
}

async function login(email: string, password: string) {
  const port = process.env.PORT || "4000";
  const res = await fetch(`http://127.0.0.1:${port}/api/auth/login`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email, password }),
  });
  const body: any = await res.json().catch(() => null);
  if (!res.ok || !body?.accessToken) throw new Error(`login failed ${res.status}`);
  return body as { accessToken: string };
}

async function main() {
  loadEnv();
  const port = process.env.PORT || "4000";
  const auth = await login("admin@safarlibya.com", "19992000");
  const headers = { Authorization: `Bearer ${auth.accessToken}` };

  const customer = await fetch(`http://127.0.0.1:${port}/api/dashboard/customer`, { headers });
  const customerBody: any = await customer.json().catch(() => null);
  const cOk =
    customer.status === 200 &&
    customerBody?._db === "mysql-hybrid" &&
    Array.isArray(customerBody?.bookings) &&
    Array.isArray(customerBody?.favorites);

  const owner = await fetch(`http://127.0.0.1:${port}/api/dashboard/owner`, { headers });
  const ownerBody: any = await owner.json().catch(() => null);
  const oOk =
    owner.status === 200 &&
    ownerBody?._db === "mysql-hybrid" &&
    Array.isArray(ownerBody?.properties);

  const admin = await fetch(`http://127.0.0.1:${port}/api/dashboard/admin`, { headers });
  const adminBody: any = await admin.json().catch(() => null);
  const aOk =
    admin.status === 200 &&
    adminBody?._db === "mysql-hybrid" &&
    typeof adminBody?.counts?.users === "number";

  console.log(`${cOk ? "PASS" : "FAIL"}  customer _db=${customerBody?._db} status=${customer.status}`);
  if (!cOk) console.log(JSON.stringify(customerBody)?.slice(0, 400));
  console.log(`${oOk ? "PASS" : "FAIL"}  owner _db=${ownerBody?._db} status=${owner.status}`);
  if (!oOk) console.log(JSON.stringify(ownerBody)?.slice(0, 400));
  console.log(`${aOk ? "PASS" : "FAIL"}  admin _db=${adminBody?._db} status=${admin.status}`);
  if (!aOk) console.log(JSON.stringify(adminBody)?.slice(0, 400));

  const ok = cOk && oOk && aOk;
  console.log(`\nSUMMARY dashboard: ${ok ? "3/3 pass" : "FAIL"}`);
  process.exit(ok ? 0 : 1);
}

main().catch((e) => {
  console.error(e instanceof Error ? e.message : e);
  process.exit(1);
});
