import { CollectionReference, Query } from 'firebase-admin/firestore';
import { ROLE_THRESHOLD, BoardAccessMode } from '../config';

export function buildQueryWithAccessControl<T = FirebaseFirestore.DocumentData>(
  baseRef: CollectionReference<T>,
  access: BoardAccessMode,
  userId: string | null,
  userRole: number,
): Query<T> {
  if (access === 'private') {
    if (!userId) {
      throw new Error('Unauthorized: Missing userId for private access');
    }
    return baseRef.where('userId', '==', userId);
  }

  if (access === 'admin') {
    if (userRole < ROLE_THRESHOLD.ADMIN) {
      throw new Error('Forbidden: Admin access only');
    }
    return baseRef;
  }

  // ✅ Public access → only show non-hidden documents unless elevated
  if (userRole < ROLE_THRESHOLD.MANAGER) {
    return baseRef.where('ishidden', '==', false);
  }

  // Managers+ can see everything in public mode
  return baseRef;
}
