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

async function run() {
  const clientRole = await db.roles.findOne({ where: { name: "Client" } });
  assert.ok(clientRole, "Client role must exist");

  const clientUser = await db.users.findOne({ where: { app_roleId: clientRole.id, disabled: false } });
  assert.ok(clientUser, "An enabled synthetic Client fixture must exist");

  const token = jwt.sign({ user: { id: clientUser.id, email: clientUser.email } }, config.secret_key, { expiresIn: "5m" });
  const headers = { Authorization: `Bearer ${token}` };
  const portalResponse = await fetch("http://127.0.0.1:3000/api/coaching/client-portal/me", { headers });
  assert.equal(portalResponse.status, 200);
  const portal = await portalResponse.json();

  for (const field of ["notes", "tags", "portalUserId", "ownerId", "private_coach_notes", "transcript_notes"]) {
    assert.equal(Object.prototype.hasOwnProperty.call(portal, field), false, `Portal leaked ${field}`);
  }

  const collectionResponse = await fetch("http://127.0.0.1:3000/api/coaching/clients", { headers });
  assert.equal(collectionResponse.status, 403);

  const aiResponse = await fetch("http://127.0.0.1:3000/api/ai/response", {
    method: "POST",
    headers: { ...headers, "Content-Type": "application/json" },
    body: JSON.stringify({ input: "blocked" }),
  });
  assert.equal(aiResponse.status, 403);

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

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