import { AuthError } from '@/lib/auth/session';
import { getCurrentUserContext } from '@/features/foundation/auth-context/service';
import { requireOrganizationAccess } from '@/features/foundation/organization-context/service';

export async function hasPermission(permission: string) {
  const context = await getCurrentUserContext();

  if (!context) {
    return false;
  }

  if (context.user.systemRole === 'super_admin') {
    return true;
  }

  return context.permissions.includes(permission);
}

export async function requirePermission(permission: string) {
  try {
    await requireOrganizationAccess({ permission });
    return true;
  } catch (error) {
    if (error instanceof AuthError) {
      throw error;
    }

    throw new AuthError('Forbidden', 403);
  }
}

export async function hasBusinessRole(role: string) {
  const context = await getCurrentUserContext();

  if (!context) {
    return false;
  }

  if (context.user.systemRole === 'super_admin') {
    return true;
  }

  return context.businessRole === role;
}
