const assert = require("node:assert/strict");
const db = require("../src/db/models");

db.sequelize.options.logging = false;

async function run() {
  const clientRole = await db.roles.findOne({ where: { name: "Client" } });
  const clientUser = await db.users.findOne({ where: { app_roleId: clientRole.id, disabled: false } });
  assert.ok(clientUser, "Enabled Client fixture is required");

  let loginPath = "/api/auth/signin/local";
  let loginBody = { email: clientUser.email, password: process.env.CLIENT_PASSWORD };

  if (process.env.DEMO_MODE === "true") {
    loginPath = "/api/auth/signin/demo";
    loginBody = { role: "client" };
  } else {
    assert.ok(process.env.CLIENT_PASSWORD, "CLIENT_PASSWORD is required for this live check");
  }

  const login = await fetch(`http://127.0.0.1:3000${loginPath}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(loginBody),
  });
  assert.equal(login.status, 200);
  const cookie = login.headers.get("set-cookie");
  assert.match(cookie, /coaching_session=/);
  assert.match(cookie, /HttpOnly/i);
  assert.match(cookie, /Secure/i);
  assert.match(cookie, /SameSite=Lax/i);
  const sessionCookie = cookie.split(";")[0];

  const me = await fetch("http://127.0.0.1:3000/api/auth/me", { headers: { Cookie: sessionCookie } });
  assert.equal(me.status, 200);

  const blockedLogout = await fetch("http://127.0.0.1:3000/api/auth/logout", {
    method: "POST",
    headers: { Cookie: sessionCookie, Origin: "https://attacker.test" },
  });
  assert.equal(blockedLogout.status, 403);

  const logout = await fetch("http://127.0.0.1:3000/api/auth/logout", {
    method: "POST",
    headers: { Cookie: sessionCookie, Origin: "http://127.0.0.1:3000" },
  });
  assert.equal(logout.status, 200);
  assert.match(logout.headers.get("set-cookie"), /Expires=Thu, 01 Jan 1970/i);

  console.log("live_cookie_auth_check=passed");
}

run()
  .then(() => db.sequelize.close())
  .catch(async (error) => {
    console.error(error);
    await db.sequelize.close();
    process.exitCode = 1;
  });
