// @ts-check
/** Fictional teaching fixtures. This simulation is not an authorization boundary.
 * @typedef {{id: string, name: string, role: string, tenantId: string, groups: readonly string[]}} Principal
 * @typedef {{id: string, title: string, team: string, tenantId: string, allowedGroups: readonly string[], allowedUsers: readonly string[], match: number, fact: string}} Evidence
 */

/** @type {readonly Principal[]} */
export const PEOPLE = [
  { id: "maya", name: "Maya", role: "Support", tenantId: "sachin", groups: ["support"] },
  { id: "arun", name: "Arun", role: "Engineering", tenantId: "sachin", groups: ["engineering"] },
];

export const QUESTION = "Why is the Orion launch delayed?";

/** @type {readonly Evidence[]} */
export const DOCUMENTS = [
  {
    id: "D1", title: "Customer launch update", team: "Shared", tenantId: "sachin",
    allowedGroups: ["support", "engineering"], allowedUsers: [], match: 87,
    fact: "Orion’s launch has moved to 14 October while the team completes reliability checks.",
  },
  {
    id: "D2", title: "Engineering incident note", team: "Engineering", tenantId: "sachin",
    allowedGroups: ["engineering"], allowedUsers: [], match: 98,
    fact: "Sign-in requests time out under peak load. The identity team is fixing the session refresh path.",
  },
  {
    id: "D3", title: "Customer support FAQ", team: "Support", tenantId: "sachin",
    allowedGroups: ["support"], allowedUsers: [], match: 82,
    fact: "Existing workspaces stay available. Customers do not need to take any action.",
  },
  {
    id: "D4", title: "Launch cost review", team: "Finance", tenantId: "sachin",
    allowedGroups: ["finance"], allowedUsers: [], match: 91,
    fact: "The delay adds $24,000 to the internal launch budget.",
  },
];

// @example:policy
/** Identity must already come from a trusted session; this function only checks permission.
 * @param {Principal | null} user @param {Evidence} chunk */
export function checkAccess(user, chunk) {
  const hasIdentity = user !== null;
  const sameCompany = hasIdentity && user.tenantId === chunk.tenantId;
  const directGrant = hasIdentity && chunk.allowedUsers.includes(user.id);
  const matchingGroups = user?.groups.filter(group => chunk.allowedGroups.includes(group)) ?? [];
  const groupGrant = matchingGroups.length > 0;
  const allowed = sameCompany && (directGrant || groupGrant);
  const reason = !hasIdentity ? "No verified identity"
    : !sameCompany ? "Different company"
    : directGrant ? "Direct user grant"
    : groupGrant ? `${matchingGroups.join(", ")} group grants access`
    : "No matching permission";

  return { hasIdentity, sameCompany, directGrant, groupGrant, matchingGroups, allowed, reason };
}
// @example:end-policy

/** @param {Principal | null} user @param {readonly Evidence[]} documents */
export function retrieveEvidence(user, documents = DOCUMENTS) {
  return documents
    .filter(chunk => checkAccess(user, chunk).allowed)
    .sort((a, b) => b.match - a.match);
}

/** @param {Principal | null} user @param {readonly Evidence[]} documents */
export function buildAnswer(user, documents = DOCUMENTS) {
  const evidence = retrieveEvidence(user, documents);
  const context = evidence.map(chunk => `[${chunk.id}] ${chunk.title}\n${chunk.fact}`).join("\n\n");
  // These are example request messages. This lesson makes no model call.
  const messages = evidence.length ? [
    { role: "system", content: "Use the supplied evidence to answer the question. Cite each source ID. If the evidence is insufficient, say so." },
    { role: "user", content: `Question: ${QUESTION}\n\nPermitted context:\n${context}` },
  ] : [];

  return {
    evidence,
    context,
    messages,
    // Assemble fixed facts to make the experiment reproducible, without a model.
    sentences: evidence.map(({ id, fact }) => ({ sourceId: id, text: fact })),
    emptyMessage: evidence.length ? null : "I don’t have accessible evidence to answer this question.",
  };
}

// Run with: node sachin-permissions.mjs
// No packages, keys, network requests, or model calls are needed.
import assert from "node:assert/strict";

const [maya, arun] = PEOPLE;
const cases = [
  { label: "Maya", user: maya, expected: ["D1", "D3"] },
  { label: "Arun", user: arun, expected: ["D2", "D1"] },
  { label: "Maya (no groups)", user: { ...maya, groups: [] }, expected: [] },
];

for (const { label, user, expected } of cases) {
  const answer = buildAnswer(user);
  const ids = answer.evidence.map(chunk => chunk.id);
  assert.deepEqual(ids, expected);
  for (const chunk of DOCUMENTS) {
    if (!checkAccess(user, chunk).allowed) {
      assert.ok(!JSON.stringify(answer.messages).includes(chunk.fact));
    }
  }
  console.log(label + ": " + (ids.join(", ") || "(none)"));
}

assert.equal(checkAccess(null, DOCUMENTS[0]).allowed, false);
const foreignChunk = { ...DOCUMENTS[0], tenantId: "another-company", allowedUsers: [maya.id] };
assert.equal(checkAccess(maya, foreignChunk).allowed, false);
assert.deepEqual(buildAnswer({ ...maya, groups: [] }).messages, []);
console.log("All permission checks passed.");

// Explore the exact example request:
// console.log(JSON.stringify(buildAnswer(maya).messages, null, 2));
