/**
 * Self-test loyalty + settings MySQL.
 */
import fs from "fs";
import path from "path";
import mysql from "mysql2/promise";

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 status=${res.status} ${JSON.stringify(body)}`);
  }
  return body as { accessToken: string; user: { id: 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 res = await fetch(`http://127.0.0.1:${port}/api/loyalty`, { headers });
  const body: any = await res.json().catch(() => null);
  const getOk =
    res.status === 200 &&
    body?._db === "mysql" &&
    body?._settingsDb === "mysql" &&
    typeof body?.points === "number" &&
    Array.isArray(body?.transactions) &&
    typeof body?.settings?.loyaltyEnabled === "boolean";

  const conn = await mysql.createConnection({
    host: process.env.MYSQL_HOST,
    port: Number(process.env.MYSQL_PORT),
    user: process.env.MYSQL_USER,
    password: process.env.MYSQL_PASSWORD,
    database: process.env.MYSQL_DATABASE,
  });

  const [acc] = await conn.query(
    `SELECT points FROM loyalty_accounts WHERE user_id = ? LIMIT 1`,
    [auth.user.id],
  );
  const accountExists = (acc as any[]).length === 1;

  const [settings] = await conn.query(
    `SELECT \`key\` FROM app_settings WHERE \`key\` = 'commerce' LIMIT 1`,
  );
  const settingsExists = (settings as any[]).length === 1;
  await conn.end();

  console.log(`${getOk ? "PASS" : "FAIL"}  get_loyalty _db=${body?._db} _settingsDb=${body?._settingsDb}`);
  console.log(`${accountExists ? "PASS" : "FAIL"}  account_persisted`);
  console.log(`${settingsExists ? "PASS" : "FAIL"}  commerce_settings_row`);
  if (!getOk) console.log("body=", JSON.stringify(body));
  const ok = getOk && accountExists && settingsExists;
  console.log(`\nSUMMARY loyalty+settings: ${ok ? "3/3 pass" : "FAIL"}`);
  process.exit(ok ? 0 : 1);
}

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