"use server";

import { prisma } from '@/lib/prisma';
import { revalidatePath } from 'next/cache';

export async function getSiteSettings() {
  try {
    const settings = await prisma.siteSetting.findUnique({
      where: { id: 'singleton' }
    });
    
    // Default fallback values if not initialized
    const defaultSettings = {
      siteName: "Afropreunariat",
      siteSlogan: "La plateforme de référence pour l'entrepreneuriat africain.",
      contactEmail: "support@afropreunariat.com",
      contactPhone: "+225 00 00 00 00 00",
      address: "Abidjan, Côte d'Ivoire",
      facebookUrl: "",
      twitterUrl: "",
      instagramUrl: "",
      linkedinUrl: "",
      footerText: "© 2025 Afropreunariat. Tous droits réservés."
    };

    if (!settings) return defaultSettings;
    return settings;
  } catch (error) {
    console.error("Failed to fetch settings:", error);
    return null;
  }
}

export async function updateSiteSettings(data: any) {
  try {
    const settings = await prisma.siteSetting.upsert({
      where: { id: 'singleton' },
      update: data,
      create: {
        id: 'singleton',
        ...data
      }
    });
    
    revalidatePath('/settings');
    revalidatePath('/', 'layout'); // Revalidate all public pages because footer/header might use it
    
    return { success: true, settings };
  } catch (error) {
    console.error("Failed to update settings:", error);
    return { success: false, error: "Erreur lors de la mise à jour des paramètres" };
  }
}
