"use server"

import { createClient } from "@/lib/supabase-server"
import { revalidatePath } from "next/cache"

export async function updateSiteSettings(data: {
    site_title: string
    site_description: string
    contact_email: string
    contact_phone: string
    currency: string
}) {
    const supabase = createClient()

    // Check admin is already handled by RLS on database level, but we can double check here
    const { data: { user } } = await supabase.auth.getUser()
    if (!user) return { error: "Oturum açmanız gerekiyor." }

    // We update the single row where id is likely 1 or just the first row
    // Since we initialized it with one row, we can just update match on something true or fetch id first.
    // Easier: Update all rows (there should only be one) or fetch the specific ID first.

    // Let's first get the ID just to be precise
    const { data: existing } = await supabase.from('site_settings').select('id').single()

    if (!existing) {
        return { error: "Ayarlar bulunamadı." }
    }

    const { error } = await supabase
        .from('site_settings')
        .update(data)
        .eq('id', existing.id)

    if (error) {
        return { error: "Ayarlar güncellenemedi: " + error.message }
    }

    revalidatePath("/dashboard/settings")
    revalidatePath("/") // Revalidate home as it might use these settings
    return { success: true }
}
