/**
 * Define RLS rules for all tables using convex-helpers
 */

import type { Rules } from 'convex-helpers/server/rowLevelSecurity';

import type { MemberRole } from '../../../../lib/shared/schemas/organizations';
import type { DataModel } from '../../../_generated/dataModel';
import type { QueryCtx } from '../../../_generated/server';
import { getUserTeamIds } from '../../get_user_teams';
import { hasTeamAccess } from '../../team_access';
import { getAuthUserIdentity } from '../auth/get_auth_user_identity';
import { getUserOrganizations } from '../organization/get_user_organizations';
import type {
  AuthenticatedUser,
  OrganizationMember,
  RLSRuleContext,
} from '../types';
import { authorizeRls } from './access_control';

/**
 * Define RLS rules for all tables
 * @param ctx - Query context
 * @param prefetchedData - Optional pre-fetched auth data to avoid duplicate queries
 */
export async function rlsRules(
  ctx: QueryCtx,
  prefetchedData?: {
    user: AuthenticatedUser | null;
    userOrganizations: Array<{
      organizationId: string;
      role: MemberRole;
      member: OrganizationMember;
    }>;
    userTeamIds: Set<string>;
  },
): Promise<Rules<RLSRuleContext, DataModel>> {
  // Use pre-fetched data if available, otherwise fetch
  const user = prefetchedData?.user ?? (await getAuthUserIdentity(ctx));
  const userOrganizations =
    prefetchedData?.userOrganizations ??
    (user ? await getUserOrganizations(ctx, user) : []);
  const userOrgIds = new Set(
    userOrganizations.map((org) => org.organizationId),
  );

  // Use pre-fetched team IDs if available (parallel fetch in queryWithRLS),
  // otherwise fetch sequentially as fallback
  const userTeamIds =
    prefetchedData?.userTeamIds ??
    (user?.userId
      ? new Set(await getUserTeamIds(ctx, user.userId))
      : new Set<string>());

  const hasDocumentTeamAccess = (doc: { teamId?: string | null }): boolean =>
    hasTeamAccess(doc, userTeamIds);

  return {
    // Agents - organization-scoped with team-based access control
    agentBindings: {
      read: async (_, agent) => {
        if (!user) return false;
        if (!userOrgIds.has(agent.organizationId)) return false;
        if (!hasTeamAccess(agent, userTeamIds)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === agent.organizationId,
        );
        return authorizeRls(membership?.role, 'agentBindings', 'read');
      },
      modify: async (_, agent) => {
        if (!user) return false;
        if (!userOrgIds.has(agent.organizationId)) return false;
        if (!hasTeamAccess(agent, userTeamIds)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === agent.organizationId,
        );
        return authorizeRls(membership?.role, 'agentBindings', 'write');
      },
      insert: async ({ user: ruleUser }, agent) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(agent.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === agent.organizationId,
        );
        return authorizeRls(membership?.role, 'agentBindings', 'write');
      },
    },

    // Documents - organization-scoped with team-based access control
    documents: {
      read: async (_, doc) => {
        if (!user) return false;
        if (!userOrgIds.has(doc.organizationId)) return false;
        if (!hasDocumentTeamAccess(doc)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === doc.organizationId,
        );
        return authorizeRls(membership?.role, 'documents', 'read');
      },
      modify: async (_, doc) => {
        if (!user) return false;
        if (!userOrgIds.has(doc.organizationId)) return false;
        if (!hasDocumentTeamAccess(doc)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === doc.organizationId,
        );
        return authorizeRls(membership?.role, 'documents', 'write');
      },
      insert: async ({ user: ruleUser }, doc) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(doc.organizationId)) return false;
        if (!hasDocumentTeamAccess(doc)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === doc.organizationId,
        );
        return authorizeRls(membership?.role, 'documents', 'write');
      },
    },

    // Projects - organization-scoped with team-based access control.
    // Per-project access (team-restriction reads) is enforced in the
    // dedicated `projects/access.ts` helpers — RLS here is the RBAC floor
    // (role + org membership). Mutation handlers further check
    // `hasProjectAccess` + admin gates for sharing/delete.
    projects: {
      read: async (_, project) => {
        if (!user) return false;
        if (!userOrgIds.has(project.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === project.organizationId,
        );
        return authorizeRls(membership?.role, 'projects', 'read');
      },
      modify: async (_, project) => {
        if (!user) return false;
        if (!userOrgIds.has(project.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === project.organizationId,
        );
        return authorizeRls(membership?.role, 'projects', 'write');
      },
      insert: async ({ user: ruleUser }, project) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(project.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === project.organizationId,
        );
        return authorizeRls(membership?.role, 'projects', 'write');
      },
    },

    // Products - organization-scoped
    products: {
      read: async (_, product) => {
        if (!user) return false;
        if (!userOrgIds.has(product.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === product.organizationId,
        );
        return authorizeRls(membership?.role, 'products', 'read');
      },
      modify: async (_, product) => {
        if (!user) return false;
        if (!userOrgIds.has(product.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === product.organizationId,
        );
        return authorizeRls(membership?.role, 'products', 'write');
      },
      insert: async ({ user: ruleUser }, product) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(product.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === product.organizationId,
        );
        return authorizeRls(membership?.role, 'products', 'write');
      },
    },

    // Customers - organization-scoped
    customers: {
      read: async (_, customer) => {
        if (!user) return false;
        if (!userOrgIds.has(customer.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === customer.organizationId,
        );
        return authorizeRls(membership?.role, 'customers', 'read');
      },
      modify: async (_, customer) => {
        if (!user) return false;
        if (!userOrgIds.has(customer.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === customer.organizationId,
        );
        return authorizeRls(membership?.role, 'customers', 'write');
      },
      insert: async ({ user: ruleUser }, customer) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(customer.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === customer.organizationId,
        );
        return authorizeRls(membership?.role, 'customers', 'write');
      },
    },

    // Vendors - organization-scoped
    vendors: {
      read: async (_, vendor) => {
        if (!user) return false;
        if (!userOrgIds.has(vendor.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === vendor.organizationId,
        );
        return authorizeRls(membership?.role, 'vendors', 'read');
      },
      modify: async (_, vendor) => {
        if (!user) return false;
        if (!userOrgIds.has(vendor.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === vendor.organizationId,
        );
        return authorizeRls(membership?.role, 'vendors', 'write');
      },
      insert: async ({ user: ruleUser }, vendor) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(vendor.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === vendor.organizationId,
        );
        return authorizeRls(membership?.role, 'vendors', 'write');
      },
    },

    // Integrations - organization-scoped, Developer+ role required for modifications
    integrations: {
      read: async (_, integration) => {
        if (!user) return false;
        if (!userOrgIds.has(integration.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === integration.organizationId,
        );
        return authorizeRls(membership?.role, 'integrations', 'read');
      },
      modify: async (_, integration) => {
        if (!user) return false;
        if (!userOrgIds.has(integration.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === integration.organizationId,
        );
        return authorizeRls(membership?.role, 'integrations', 'write');
      },
      insert: async ({ user: ruleUser }, integration) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(integration.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === integration.organizationId,
        );
        return authorizeRls(membership?.role, 'integrations', 'write');
      },
    },

    // Integration Credentials - organization-scoped, Developer+ role required for modifications
    integrationCredentials: {
      read: async (_, cred) => {
        if (!user) return false;
        if (!userOrgIds.has(cred.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === cred.organizationId,
        );
        return authorizeRls(membership?.role, 'integrationCredentials', 'read');
      },
      modify: async (_, cred) => {
        if (!user) return false;
        if (!userOrgIds.has(cred.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === cred.organizationId,
        );
        return authorizeRls(
          membership?.role,
          'integrationCredentials',
          'write',
        );
      },
      insert: async ({ user: ruleUser }, cred) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(cred.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === cred.organizationId,
        );
        return authorizeRls(
          membership?.role,
          'integrationCredentials',
          'write',
        );
      },
    },

    // OneDrive Sync Configs - organization-scoped
    onedriveSyncConfigs: {
      read: async (_, config) => {
        if (!user) return false;
        if (!userOrgIds.has(config.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === config.organizationId,
        );
        return authorizeRls(membership?.role, 'onedriveSyncConfigs', 'read');
      },
      modify: async (_, config) => {
        if (!user) return false;
        if (!userOrgIds.has(config.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === config.organizationId,
        );
        return authorizeRls(membership?.role, 'onedriveSyncConfigs', 'write');
      },
      insert: async ({ user: ruleUser }, config) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(config.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === config.organizationId,
        );
        return authorizeRls(membership?.role, 'onedriveSyncConfigs', 'write');
      },
    },

    // Conversations - organization-scoped
    conversations: {
      read: async (_, conversation) => {
        if (!user) return false;
        if (!userOrgIds.has(conversation.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === conversation.organizationId,
        );
        return authorizeRls(membership?.role, 'conversations', 'read');
      },
      modify: async (_, conversation) => {
        if (!user) return false;
        if (!userOrgIds.has(conversation.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === conversation.organizationId,
        );
        return authorizeRls(membership?.role, 'conversations', 'write');
      },
      insert: async ({ user: ruleUser }, conversation) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(conversation.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === conversation.organizationId,
        );
        return authorizeRls(membership?.role, 'conversations', 'write');
      },
    },

    // Conversation Messages - organization-scoped
    conversationMessages: {
      read: async (_, message) => {
        if (!user) return false;
        if (!userOrgIds.has(message.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === message.organizationId,
        );
        return authorizeRls(membership?.role, 'conversationMessages', 'read');
      },
      modify: async (_, message) => {
        if (!user) return false;
        if (!userOrgIds.has(message.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === message.organizationId,
        );
        return authorizeRls(membership?.role, 'conversationMessages', 'write');
      },
      insert: async ({ user: ruleUser }, message) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(message.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === message.organizationId,
        );
        return authorizeRls(membership?.role, 'conversationMessages', 'write');
      },
    },

    // @deprecated — DB table deprecated; RLS rules kept for legacy data access only
    wfDefinitions: {
      read: async (_, wf) => {
        if (!user) return false;
        if (!userOrgIds.has(wf.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === wf.organizationId,
        );
        return authorizeRls(membership?.role, 'wfDefinitions', 'read');
      },
      modify: async (_, wf) => {
        if (!user) return false;
        if (!userOrgIds.has(wf.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === wf.organizationId,
        );
        return authorizeRls(membership?.role, 'wfDefinitions', 'write');
      },
      insert: async ({ user: ruleUser }, wf) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(wf.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === wf.organizationId,
        );
        return authorizeRls(membership?.role, 'wfDefinitions', 'write');
      },
    },

    // @deprecated — DB table deprecated; RLS rules kept for legacy data access only
    wfStepDefs: {
      read: async (_, step) => {
        if (!user) return false;
        if (!userOrgIds.has(step.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === step.organizationId,
        );
        return authorizeRls(membership?.role, 'wfStepDefs', 'read');
      },
      modify: async (_, step) => {
        if (!user) return false;
        if (!userOrgIds.has(step.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === step.organizationId,
        );
        return authorizeRls(membership?.role, 'wfStepDefs', 'write');
      },
      insert: async ({ user: ruleUser }, step) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(step.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === step.organizationId,
        );
        return authorizeRls(membership?.role, 'wfStepDefs', 'write');
      },
    },

    // Workflow Executions - organization-scoped
    wfExecutions: {
      read: async (_, exec) => {
        if (!user) return false;
        if (!userOrgIds.has(exec.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === exec.organizationId,
        );
        return authorizeRls(membership?.role, 'wfExecutions', 'read');
      },
      modify: async (_, exec) => {
        if (!user) return false;
        if (!userOrgIds.has(exec.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === exec.organizationId,
        );
        return authorizeRls(membership?.role, 'wfExecutions', 'write');
      },
      insert: async ({ user: ruleUser }, exec) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(exec.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === exec.organizationId,
        );
        return authorizeRls(membership?.role, 'wfExecutions', 'write');
      },
    },

    // Workflow Approvals - organization-scoped
    approvals: {
      read: async (_, approval) => {
        if (!user) return false;
        if (!userOrgIds.has(approval.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === approval.organizationId,
        );
        return authorizeRls(membership?.role, 'approvals', 'read');
      },
      modify: async (_, approval) => {
        if (!user) return false;
        if (!userOrgIds.has(approval.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === approval.organizationId,
        );
        return authorizeRls(membership?.role, 'approvals', 'write');
      },
      insert: async ({ user: ruleUser }, approval) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(approval.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === approval.organizationId,
        );
        return authorizeRls(membership?.role, 'approvals', 'write');
      },
    },

    // Websites - organization-scoped
    websites: {
      read: async (_, website) => {
        if (!user) return false;
        if (!userOrgIds.has(website.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === website.organizationId,
        );
        return authorizeRls(membership?.role, 'websites', 'read');
      },
      modify: async (_, website) => {
        if (!user) return false;
        if (!userOrgIds.has(website.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === website.organizationId,
        );
        return authorizeRls(membership?.role, 'websites', 'write');
      },
      insert: async ({ user: ruleUser }, website) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(website.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === website.organizationId,
        );
        return authorizeRls(membership?.role, 'websites', 'write');
      },
    },

    // Prompt Templates - organization-scoped, team-filtered
    promptTemplates: {
      read: async (_, prompt) => {
        if (!user) return false;
        if (!userOrgIds.has(prompt.organizationId)) return false;
        if (!hasTeamAccess(prompt, userTeamIds)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === prompt.organizationId,
        );
        return authorizeRls(membership?.role, 'promptTemplates', 'read');
      },
      modify: async (_, prompt) => {
        if (!user) return false;
        if (!userOrgIds.has(prompt.organizationId)) return false;
        if (!hasTeamAccess(prompt, userTeamIds)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === prompt.organizationId,
        );
        return authorizeRls(membership?.role, 'promptTemplates', 'write');
      },
      insert: async ({ user: ruleUser }, prompt) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(prompt.organizationId)) return false;
        if (!hasTeamAccess(prompt, userTeamIds)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === prompt.organizationId,
        );
        return authorizeRls(membership?.role, 'promptTemplates', 'write');
      },
    },

    // Prompt Categories - organization-scoped, scope-filtered
    // (personal: creator; team: team members; global: any org member).
    // Coarse RLS — the handler still does scope-specific create gating
    // (admins for team/global, creator-only for personal modify).
    promptCategories: {
      read: async (_, category) => {
        if (!user) return false;
        if (!userOrgIds.has(category.organizationId)) return false;
        if (category.scope === 'global') {
          // visible to any org member
        } else if (category.scope === 'team') {
          if (!category.teamId || !userTeamIds.has(category.teamId))
            return false;
        } else if (category.scope === 'personal') {
          if (category.createdBy !== user.userId) return false;
        } else {
          return false;
        }
        const membership = userOrganizations.find(
          (m) => m.organizationId === category.organizationId,
        );
        return authorizeRls(membership?.role, 'promptCategories', 'read');
      },
      modify: async (_, category) => {
        if (!user) return false;
        if (!userOrgIds.has(category.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === category.organizationId,
        );
        if (!authorizeRls(membership?.role, 'promptCategories', 'write')) {
          return false;
        }
        // Mirror the scope model on the write path so the row policy
        // doesn't rely on every caller to remember the matrix:
        //   personal — only the creator
        //   team     — admins/owners of the org who are members of the team
        //   global   — admins/owners only
        const isAdminRole =
          membership?.role === 'admin' || membership?.role === 'owner';
        if (category.scope === 'personal') {
          return category.createdBy === user.userId;
        }
        if (category.scope === 'team') {
          if (!isAdminRole) return false;
          return !!category.teamId && userTeamIds.has(category.teamId);
        }
        if (category.scope === 'global') {
          return isAdminRole;
        }
        return false;
      },
      insert: async ({ user: ruleUser }, category) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(category.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === category.organizationId,
        );
        if (!authorizeRls(membership?.role, 'promptCategories', 'write')) {
          return false;
        }
        const isAdminRole =
          membership?.role === 'admin' || membership?.role === 'owner';
        if (category.scope === 'personal') {
          return category.createdBy === ruleUser.userId;
        }
        if (category.scope === 'team') {
          if (!isAdminRole) return false;
          return !!category.teamId && userTeamIds.has(category.teamId);
        }
        if (category.scope === 'global') {
          return isAdminRole;
        }
        return false;
      },
    },

    // Audit Log Chain Genesis - internal per-org serialization sentinel for
    // the audit hash chain (see audit_logs/schema.ts). Carries no user data.
    // Writes happen exclusively through internalMutation (createAuditLog),
    // which bypasses RLS, so the user-facing gate is deny-all. Surfacing
    // this sentinel to clients would leak per-org write-rate metadata
    // (round-2 R2-B8).
    auditLogChainGenesis: {
      read: async () => false,
      insert: async () => false,
      modify: async () => false,
    },

    // Audit Logs - organization-scoped, allow inserts for org members
    auditLogs: {
      read: async (_, log) => {
        if (!user) return false;
        if (!userOrgIds.has(log.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === log.organizationId,
        );
        return authorizeRls(membership?.role, 'auditLogs', 'read');
      },
      // Audit-log row content is immutable; the chain hash + verifyIntegrity
      // job enforce that. Convex-helpers RLS only sees the document, not the
      // patch diff, so we cannot block "edit field X" while allowing the
      // forward-chain link patch (chainSuccessor) that createAuditLog must
      // perform on the predecessor row to serialize concurrent writers via
      // OCC. Gate modify on org membership; any tampering with other fields
      // is caught by the next write's self-check against the recomputed hash.
      modify: async (_, log) => {
        if (!user) return false;
        return userOrgIds.has(log.organizationId);
      },
      insert: async ({ user: ruleUser }, log) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(log.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === log.organizationId,
        );
        return authorizeRls(membership?.role, 'auditLogs', 'write');
      },
    },

    // Sandbox Executions - audit table. Reads go through the role
    // matrix (members can READ their org's history); writes happen
    // exclusively through internalMutation (reserveSlotAndInsert /
    // finalize / recoverStuckSandboxes) which bypasses RLS, so the
    // user-facing modify/insert remain deny-all.
    sandboxExecutions: {
      read: async (_, exec) => {
        if (!user) return false;
        if (!userOrgIds.has(exec.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === exec.organizationId,
        );
        return authorizeRls(membership?.role, 'sandboxExecutions', 'read');
      },
      modify: async () => false,
      insert: async () => false,
    },

    // Workflow Step Audit Logs - organization-scoped, allow inserts for org members
    wfStepAuditLogs: {
      read: async (_, log) => {
        if (!user) return false;
        if (!userOrgIds.has(log.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === log.organizationId,
        );
        return authorizeRls(membership?.role, 'wfStepAuditLogs', 'read');
      },
      modify: async () => false, // Audit logs are immutable
      insert: async ({ user: ruleUser }, log) => {
        if (!ruleUser) return false;
        if (!userOrgIds.has(log.organizationId)) return false;
        const membership = userOrganizations.find(
          (m) => m.organizationId === log.organizationId,
        );
        return authorizeRls(membership?.role, 'wfStepAuditLogs', 'write');
      },
    },
  } satisfies Rules<RLSRuleContext, DataModel>;
}
