/**
 * Self-test auth + uploads verification-status (MySQL).
 */
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 main() {
  loadEnv();
  const port = process.env.PORT || "4000";
  const base = `http://127.0.0.1:${port}/api`;
  const results: { name: string; pass: boolean; detail: string }[] = [];
  const check = (name: string, pass: boolean, detail: string) => {
    results.push({ name, pass, detail });
    console.log(`${pass ? "PASS" : "FAIL"}  ${name} — ${detail}`);
  };

  const loginRes = await fetch(`${base}/auth/login`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email: "admin@safarlibya.com", password: "19992000" }),
  });
  const loginBody: any = await loginRes.json().catch(() => null);
  check(
    "login",
    loginRes.status === 200 && loginBody?._db === "mysql" && !!loginBody?.accessToken,
    `status=${loginRes.status} _db=${loginBody?._db}`,
  );

  const headers = { Authorization: `Bearer ${loginBody?.accessToken}` };

  const meRes = await fetch(`${base}/auth/me`, { headers });
  const meBody: any = await meRes.json().catch(() => null);
  check(
    "me",
    meRes.status === 200 && meBody?._db === "mysql" && meBody?.user?.email === "admin@safarlibya.com",
    `status=${meRes.status} _db=${meBody?._db}`,
  );

  const refreshRes = await fetch(`${base}/auth/refresh`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ refreshToken: loginBody?.refreshToken }),
  });
  const refreshBody: any = await refreshRes.json().catch(() => null);
  check(
    "refresh",
    refreshRes.status === 200 && refreshBody?._db === "mysql" && !!refreshBody?.accessToken,
    `status=${refreshRes.status} _db=${refreshBody?._db}`,
  );

  const logoutRes = await fetch(`${base}/auth/logout`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ refreshToken: refreshBody?.refreshToken }),
  });
  const logoutBody: any = await logoutRes.json().catch(() => null);
  check(
    "logout",
    logoutRes.status === 200 && logoutBody?._db === "mysql" && logoutBody?.ok === true,
    `status=${logoutRes.status}`,
  );

  // Re-login for uploads status (admin is staff; requireRoles OWNER|ADMIN allows via hasRole)
  const login2 = await fetch(`${base}/auth/login`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email: "admin@safarlibya.com", password: "19992000" }),
  });
  const login2Body: any = await login2.json().catch(() => null);
  const headers2 = { Authorization: `Bearer ${login2Body?.accessToken}` };

  const verRes = await fetch(`${base}/uploads/verification-status`, { headers: headers2 });
  const verBody: any = await verRes.json().catch(() => null);
  check(
    "uploads_verification_status",
    verRes.status === 200 && verBody?._db === "mysql",
    `status=${verRes.status} _db=${verBody?._db}`,
  );

  const profileRes = await fetch(`${base}/auth/profile`, {
    method: "PATCH",
    headers: { ...headers2, "Content-Type": "application/json" },
    body: JSON.stringify({ locale: meBody?.user?.locale === "ar" ? "ar" : "ar" }),
  });
  const profileBody: any = await profileRes.json().catch(() => null);
  check(
    "profile_patch",
    profileRes.status === 200 && profileBody?._db === "mysql",
    `status=${profileRes.status}`,
  );

  const failed = results.filter((r) => !r.pass).length;
  console.log(`\nSUMMARY auth+uploads: ${results.length - failed}/${results.length} pass (failed=${failed})`);
  process.exit(failed ? 1 : 0);
}

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