/**
 * Create RLS context for organization-scoped operations using Better Auth
 */

import type { QueryCtx, MutationCtx } from '../../../_generated/server';
import { requireAuthenticatedUser } from '../auth/require_authenticated_user';
import { isAdmin } from '../helpers/role_helpers';
import { getOrganizationMember } from '../organization/get_organization_member';
import type { AuthenticatedUser, RLSContext } from '../types';

/**
 * Create RLS context for organization-scoped operations
 * Uses Better Auth's organization and member system
 */
export async function createRLSContext(
  ctx: QueryCtx | MutationCtx,
  organizationId: string,
  user?: AuthenticatedUser,
): Promise<RLSContext> {
  const authUser = user ?? (await requireAuthenticatedUser(ctx));
  const member = await getOrganizationMember(ctx, organizationId, authUser);

  const role = member.role || 'member';

  return {
    user: authUser,
    member,
    organizationId,
    role,
    isAdmin: isAdmin(role),
  };
}
