import { createExecutor, recordUpdatedTrigger } from "@tailor-platform/sdk";
import { role } from "../db/role";
import { getDB } from "../generated/kysely-tailordb";
import { recomputePermissionsForUsersWithRole } from "../lib/recomputeUserPermissions";

/**
 * Executor: recomputeOnRolePermissionsUpdated
 *
 * Triggers when a Role record is updated and the permissions array has changed.
 * Recomputes effective permissions for all users with that role asynchronously.
 */
export const recomputeOnRolePermissionsUpdated = function recomputeOnRolePermissionsUpdated({
  namespace,
}: {
  namespace: string;
}) {
  return createExecutor({
    name: "recompute-on-role-permissions-updated",
    description: "Recompute permissions for all users when a role's permissions array changes",
    trigger: recordUpdatedTrigger({
      type: role,
    }),
    operation: {
      kind: "jobFunction",
      body: async ({ newRecord, oldRecord }) => {
        // Only recompute if permissions actually changed
        const oldPerms = JSON.stringify(oldRecord.permissions ?? []);
        const newPerms = JSON.stringify(newRecord.permissions ?? []);
        if (oldPerms === newPerms) return;

        // @ts-expect-error unsure at build time
        const db = getDB(namespace);
        await recomputePermissionsForUsersWithRole(db, newRecord.id);
      },
    },
  });
};
