'use server'

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

export async function saveSettings(_prevState: unknown, formData: FormData) {
  const restaurant_name = formData.get('restaurant_name') as string
  const location = formData.get('location') as string
  const logo_url = formData.get('logo_url') as string

  try {
    await prisma.$transaction([
      prisma.settings.upsert({
        where: { key: 'restaurant_name' },
        update: { value: restaurant_name },
        create: { key: 'restaurant_name', value: restaurant_name },
      }),
      prisma.settings.upsert({
        where: { key: 'location' },
        update: { value: location },
        create: { key: 'location', value: location },
      }),
      prisma.settings.upsert({
        where: { key: 'logo_url' },
        update: { value: logo_url || '' },
        create: { key: 'logo_url', value: logo_url || '' },
      }),
    ])

    revalidatePath('/')
    revalidatePath('/admin/settings')
    
    return { success: true, message: 'Ayarlar başarıyla kaydedildi.' }
  } catch (error) {
    console.error('Settings save error:', error)
    return { error: 'Ayarlar kaydedilirken bir hata oluştu.' }
  }
}
