import {
  createMembershipOperation,
  createRoleAssignmentOperation,
  createTenantOperation,
  createWorkspaceOperation
} from "./chunk-4YQD4PFR.mjs";
import "./chunk-BUAYVN3C.mjs";
import "./chunk-5S6VFBLT.mjs";
import "./chunk-I6LUPJUY.mjs";
import "./chunk-QJDHVMKT.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 {
  getDynamoControlService
} from "./chunk-EUIP2U5F.mjs";
import "./chunk-TRY7JGWO.mjs";
import "./chunk-KMEWULMX.mjs";
import "./chunk-LZOMFHX3.mjs";

// src/workflows/control-plane/user-onboarding/provision-default-workspace.handler.ts
import { createHash } from "crypto";
import { extractSummary } from "@openhi/types";
var CURRENT_SK = "CURRENT";
var VID = "1";
var summaryFor = (resource) => {
  return JSON.stringify(extractSummary(resource));
};
var stableOnboardingId = (kind, cognitoSub) => {
  return createHash("sha256").update(kind).update("\0").update(cognitoSub).digest("hex").slice(0, 26).toUpperCase();
};
var handler = async (event) => {
  const detail = event.detail;
  if (!detail?.cognitoSub) {
    console.warn(
      "ProvisionDefaultWorkspace: event missing cognitoSub; skipping"
    );
    return;
  }
  const service = getDynamoControlService();
  const existingUser = await findUserBySubOperation({
    context: {
      tenantId: "",
      workspaceId: "",
      date: "",
      actorId: "",
      actorName: "",
      actorType: "internal-system"
    },
    cognitoSub: detail.cognitoSub
  });
  const existingResource = existingUser ? parseUserResource(existingUser.resource) : void 0;
  const existingTenantId = idFromReference(
    existingResource?.currentTenant?.reference,
    "Tenant/"
  );
  const existingWorkspaceId = idFromReference(
    existingResource?.currentWorkspace?.reference,
    "Workspace/"
  );
  if (existingUser && existingTenantId && existingWorkspaceId) {
    return;
  }
  const displayName = detail.displayName || detail.email || event.resources?.[0] || detail.cognitoSub;
  const userId = existingUser?.id ?? detail.userId ?? stableOnboardingId("user", detail.cognitoSub);
  const tenantId = stableOnboardingId("tenant", detail.cognitoSub);
  const workspaceId = stableOnboardingId("workspace", detail.cognitoSub);
  const userTenantMembershipId = stableOnboardingId(
    "tenant-membership",
    detail.cognitoSub
  );
  const userWorkspaceMembershipId = stableOnboardingId(
    "workspace-membership",
    detail.cognitoSub
  );
  const roleAssignmentId = stableOnboardingId(
    "tenant-user-role-assignment",
    detail.cognitoSub
  );
  const lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
  const context = {
    tenantId,
    workspaceId,
    date: lastUpdated,
    actorId: userId,
    actorName: displayName,
    actorType: "internal-system"
  };
  const tenantResource = {
    id: tenantId,
    name: `${displayName}'s Practice`,
    active: true
  };
  const workspaceResource = {
    id: workspaceId,
    name: "Default Workspace",
    active: true,
    tenant: { reference: `Tenant/${tenantId}` }
  };
  const userResource = {
    ...existingResource ?? {},
    resourceType: "User",
    id: userId,
    name: existingResource?.name ?? [{ text: displayName }],
    status: "active",
    currentTenant: { reference: `Tenant/${tenantId}` },
    currentWorkspace: { reference: `Workspace/${workspaceId}` }
  };
  const userTenantMembershipResource = {
    id: userTenantMembershipId,
    status: "active",
    user: { reference: `User/${userId}` },
    tenant: { reference: `Tenant/${tenantId}` }
  };
  const userWorkspaceMembershipResource = {
    id: userWorkspaceMembershipId,
    status: "active",
    user: { reference: `User/${userId}` },
    tenant: { reference: `Tenant/${tenantId}` },
    workspace: { reference: `Workspace/${workspaceId}` }
  };
  const roleAssignmentResource = {
    id: roleAssignmentId,
    status: "active",
    user: { reference: `User/${userId}` },
    tenant: { reference: `Tenant/${tenantId}` },
    role: "tenant-user"
  };
  await createTenantOperation({
    context,
    body: { id: tenantId, resource: tenantResource }
  });
  await createWorkspaceOperation({
    context,
    body: { id: workspaceId, resource: workspaceResource }
  });
  if (existingUser) {
    await service.entities.user.patch({ id: userId, sk: CURRENT_SK }).set({
      resource: JSON.stringify(userResource),
      summary: summaryFor(userResource),
      cognitoSub: detail.cognitoSub,
      vid: VID,
      lastUpdated
    }).go();
  } else {
    await service.entities.user.put({
      id: userId,
      cognitoSub: detail.cognitoSub,
      resource: JSON.stringify(userResource),
      summary: summaryFor(userResource),
      vid: VID,
      lastUpdated
    }).go();
  }
  await createMembershipOperation({
    context,
    body: {
      id: userTenantMembershipId,
      resource: userTenantMembershipResource
    }
  });
  await createMembershipOperation({
    context,
    body: {
      id: userWorkspaceMembershipId,
      resource: userWorkspaceMembershipResource
    }
  });
  await createRoleAssignmentOperation({
    context,
    body: { id: roleAssignmentId, resource: roleAssignmentResource }
  });
};
export {
  handler
};
//# sourceMappingURL=provision-default-workspace.handler.mjs.map