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

/**
 * Executor: recomputeOnRolePermissionCreated
 *
 * Triggers when a RolePermission record is created (permission assigned to role).
 * Recomputes permissions for all users with that role asynchronously.
 */

export const recomputeOnRolePermissionCreated = function recomputeOnRolePermissionCreated({
  namespace,
}: {
  namespace: string;
}) {
  return createExecutor({
    name: "recompute-on-role-permission-created",
    description: "Recompute permissions for all users when a permission is assigned to a role",
    trigger: recordCreatedTrigger({
      type: rolePermission,
    }),
    operation: {
      kind: "jobFunction",
      body: async ({ newRecord }) => {
        // @ts-expect-error unsure at build time
        const db = getDB(namespace);
        await recomputePermissionsForUsersWithRole(db, newRecord.roleId);
      },
    },
  });
};

/**
 * Executor: recomputeOnRolePermissionDeleted
 *
 * Triggers when a RolePermission record is deleted (permission revoked from role).
 * Recomputes permissions for all users with that role asynchronously.
 */
export const recomputeOnRolePermissionDeleted = function recomputeOnRolePermissionDeleted({
  namespace,
}: {
  namespace: string;
}) {
  return createExecutor({
    name: "recompute-on-role-permission-deleted",
    description: "Recompute permissions for all users when a permission is revoked from a role",
    trigger: recordDeletedTrigger({
      type: rolePermission,
    }),
    operation: {
      kind: "jobFunction",
      body: async ({ oldRecord }) => {
        // @ts-expect-error unsure at build time
        const db = getDB(namespace);
        await recomputePermissionsForUsersWithRole(db, oldRecord.roleId);
      },
    },
  });
};
