import { prisma } from "./prisma";

/**
 * Retrieves a setting value from the database.
 * Falls back to environment variables if not found in database.
 */
export async function getSetting(key: string, envFallback?: string): Promise<string | undefined> {
  try {
    const setting = await prisma.setting.findUnique({
      where: { key }
    });
    
    if (setting?.value) {
      return setting.value;
    }
    
    // Fallback to environment variable if provided or if it matches the key
    return process.env[envFallback || key];
  } catch (error) {
    console.error(`Error fetching setting ${key}:`, error);
    return process.env[envFallback || key];
  }
}

/**
 * Specialized helper for API keys that might have multiple names
 */
export async function getApiKey(service: 'google' | 'foursquare' | 'apify'): Promise<string | undefined> {
  switch (service) {
    case 'google':
      return (await getSetting('GOOGLE_PLACES_API_KEY')) || process.env.GOOGLE_MAPS_API_KEY;
    case 'foursquare':
      return await getSetting('FOURSQUARE_API_KEY');
    case 'apify':
      return await getSetting('APIFY_API_TOKEN');
    default:
      return undefined;
  }
}
