import {
  listPractitionerRolesOperation,
  listRoleAssignmentsOperation
} from "./chunk-63POQTMP.mjs";
import {
  listMembershipsOperation
} from "./chunk-RGE4WDND.mjs";
import {
  findUserBySubOperation,
  idFromReference,
  parseUserResource
} from "./chunk-UWVPF6GB.mjs";
import "./chunk-6BB4CRSS.mjs";
import "./chunk-V6AO5T57.mjs";
import "./chunk-APVVG7BO.mjs";
import "./chunk-FYHBHHWK.mjs";
import "./chunk-EUIP2U5F.mjs";
import "./chunk-TRY7JGWO.mjs";
import "./chunk-LZOMFHX3.mjs";

// src/components/cognito/pre-token-generation.handler.ts
import {
  getLinkedDataIdentity,
  organizationRoleCodeSchema,
  platformRoleCodeSchema
} from "@openhi/types";
var REFERENCE_TYPES = {
  Tenant: "Tenant/",
  Workspace: "Workspace/"
};
function displayNameFor(user) {
  const names = user.name;
  const first = names?.[0];
  return first?.text ?? first?.family ?? void 0;
}
var lookupContext = {
  tenantId: "",
  workspaceId: "",
  date: "",
  actorId: "",
  actorName: "",
  actorType: "internal-system"
};
async function resolveClaims(cognitoSub) {
  const user = await findUserBySubOperation({
    context: lookupContext,
    cognitoSub
  });
  if (!user) {
    console.warn(
      `PreTokenGeneration: no User found for cognitoSub; emitting token without OpenHI claims (sub=${cognitoSub})`
    );
    return void 0;
  }
  const parsed = parseUserResource(user.resource);
  if (!parsed) {
    console.warn(
      `PreTokenGeneration: User resource JSON could not be parsed (sub=${cognitoSub}, id=${user.id})`
    );
    return void 0;
  }
  const tenantId = idFromReference(
    parsed.currentTenant?.reference,
    REFERENCE_TYPES.Tenant
  );
  const workspaceId = idFromReference(
    parsed.currentWorkspace?.reference,
    REFERENCE_TYPES.Workspace
  );
  const displayName = displayNameFor(parsed);
  if (!tenantId || !workspaceId || !displayName) {
    console.warn(
      `PreTokenGeneration: resolved User missing currentTenant/currentWorkspace/name; emitting token without OpenHI claims (sub=${cognitoSub}, id=${user.id})`
    );
    return void 0;
  }
  const [ohi_organization_roles, ohi_platform_roles] = await Promise.all([
    resolveOrganizationRoles(tenantId, workspaceId, user.id),
    resolvePlatformRoles(tenantId, workspaceId, user.id)
  ]);
  return {
    ohi_tid: tenantId,
    ohi_wid: workspaceId,
    ohi_uid: user.id,
    ohi_uname: displayName,
    ...ohi_organization_roles !== void 0 ? { ohi_organization_roles } : {},
    ...ohi_platform_roles !== void 0 ? { ohi_platform_roles } : {}
  };
}
async function resolveOrganizationRoles(tenantId, workspaceId, userId) {
  const claimContext = {
    ...lookupContext,
    tenantId,
    workspaceId
  };
  const memberships = await listMembershipsOperation({
    context: claimContext,
    mode: "full"
  });
  const userRef = `User/${userId}`;
  const workspaceRef = `Workspace/${workspaceId}`;
  const matching = memberships.entries.find((entry) => {
    const r = entry.resource;
    return r.user?.reference === userRef && r.workspace?.reference === workspaceRef;
  });
  if (matching === void 0) {
    return void 0;
  }
  const linked = getLinkedDataIdentity(
    matching.resource
  );
  if (linked?.reference === void 0) {
    return void 0;
  }
  const practitionerRoleList = await listPractitionerRolesOperation({
    context: claimContext,
    mode: "full"
  });
  const organizationRef = `Organization/${workspaceId}`;
  const codes = /* @__PURE__ */ new Set();
  for (const entry of practitionerRoleList.entries) {
    const role = entry.resource;
    if (role.practitioner?.reference !== linked.reference) continue;
    if (role.organization?.reference !== organizationRef) continue;
    const codings = role.code?.flatMap((cc) => cc.coding ?? []) ?? [];
    for (const c of codings) {
      if (typeof c.code !== "string") continue;
      const parsed = organizationRoleCodeSchema.safeParse(c.code);
      if (parsed.success) {
        codes.add(parsed.data);
      }
    }
  }
  return Array.from(codes);
}
async function resolvePlatformRoles(tenantId, workspaceId, userId) {
  const claimContext = {
    ...lookupContext,
    tenantId,
    workspaceId
  };
  const assignments = await listRoleAssignmentsOperation({
    context: claimContext,
    mode: "full"
  });
  const userRef = `User/${userId}`;
  const workspaceRef = `Workspace/${workspaceId}`;
  const userAssignments = assignments.entries.filter((entry) => {
    const r = entry.resource;
    if (r.user?.reference !== userRef) return false;
    const wsRef = r.workspace?.reference;
    return wsRef === void 0 || wsRef === workspaceRef;
  });
  if (userAssignments.length === 0) {
    return void 0;
  }
  const codes = /* @__PURE__ */ new Set();
  for (const entry of userAssignments) {
    const r = entry.resource;
    const ref = r.role?.reference;
    if (typeof ref !== "string") continue;
    const roleId = idFromReference(ref, "Role/");
    if (roleId === void 0) continue;
    const candidate = roleId.startsWith("role-") ? roleId.slice("role-".length) : roleId;
    const parsed = platformRoleCodeSchema.safeParse(candidate);
    if (parsed.success) {
      codes.add(parsed.data);
    }
  }
  return Array.from(codes);
}
function placeholderClaims() {
  return {
    ohi_tid: "placeholder-tenant-id",
    ohi_wid: "placeholder-workspace-id",
    ohi_uid: "placeholder-user-id",
    ohi_uname: "placeholder"
  };
}
function stampClaims(event, claims) {
  if (!event.response) {
    event.response = {};
  }
  const response = event.response;
  response.claimsAndScopeOverrideDetails = {
    accessTokenGeneration: {
      claimsToAddOrOverride: { ...claims }
    },
    idTokenGeneration: {
      claimsToAddOrOverride: { ...claims }
    }
  };
}
var handler = async (event, _context) => {
  try {
    const cognitoSub = event.request?.userAttributes?.sub;
    if (!cognitoSub) {
      console.warn(
        "PreTokenGeneration: event has no Cognito sub; returning event unchanged"
      );
      return event;
    }
    const resolved = await resolveClaims(cognitoSub);
    stampClaims(event, resolved ?? placeholderClaims());
  } catch (err) {
    console.warn(
      "PreTokenGeneration: unexpected error; stamping placeholder claims",
      err
    );
    try {
      stampClaims(event, placeholderClaims());
    } catch (stampErr) {
      console.warn(
        "PreTokenGeneration: failed to stamp placeholder claims after error; returning event unchanged",
        stampErr
      );
    }
  }
  return event;
};
export {
  handler
};
//# sourceMappingURL=pre-token-generation.handler.mjs.map