import { UserRole, UserStatus } from '@prisma/client';
import { prisma } from '../config/database';
import { siteSettingsService } from '../modules/settings/settings.service';
import { logger } from '../utils/logger';

/**
 * Fetch email addresses for active admin users with the specified role(s).
 */
export async function getAdminEmailsByRole(roles: UserRole[]): Promise<string[]> {
  const users = await prisma.user.findMany({
    where: {
      role: { in: roles },
      status: UserStatus.ACTIVE,
    },
    select: { email: true },
  });
  return users.map((u) => u.email);
}

/**
 * Check whether a specific notification toggle is enabled in SiteSettings.
 * Fail-open: returns true if the field is missing or settings query fails.
 */
export async function isNotificationEnabled(key: string): Promise<boolean> {
  try {
    const settings = await siteSettingsService.get();
    const value = (settings as Record<string, unknown>)[key];
    return value !== false;
  } catch (err) {
    logger.warn(`Failed to read notification setting "${key}", defaulting to enabled:`, err);
    return true;
  }
}
