'use server'

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

export async function updateSiteContent(contents: SiteContent[]) {
    const supabase = await createClient()

    try {
        const { data: { user } } = await supabase.auth.getUser()

        if (!user) {
            return { success: false, error: "Oturum açmanız gerekiyor" }
        }

        // Upsert each content item
        // Since we might have many items, we can do this in parallel or a single upsert if the structure allows
        // Supabase upsert accepts an array
        const { error } = await supabase
            .from('site_contents')
            .upsert(
                contents.map(item => ({
                    key: item.key,
                    value: item.value,
                    type: item.type,
                    section: item.section,
                    updated_at: new Date().toISOString()
                }))
            )

        if (error) {
            console.error('CMS Update Error:', error)
            return { success: false, error: "Güncelleme sırasında bir hata oluştu: " + error.message }
        }

        revalidatePath('/dashboard/cms/content')
        revalidatePath('/') // Revalidate home page as it likely uses these settings

        return { success: true }
    } catch (error) {
        console.error('CMS Update Error:', error)
        return { success: false, error: "Bir hata oluştu" }
    }
}
