"use server"

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

// Admin client for privileged operations
const supabaseAdmin = createSupabaseClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.SUPABASE_SERVICE_ROLE_KEY!,
    {
        auth: {
            autoRefreshToken: false,
            persistSession: false
        }
    }
)

async function assertAdmin() {
    const supabase = createClient()
    const { data: { user } } = await supabase.auth.getUser()
    if (!user) throw new Error("Oturum açmanız gerekiyor.")

    const { data: profile } = await supabase.from('profiles').select('role').eq('id', user.id).single()
    if (profile?.role !== 'admin') throw new Error("Yetkisiz işlem.")

    return user
}

export async function getSliders() {
    const supabase = createClient()
    // Everyone can read, so normal client is fine
    const { data, error } = await supabase
        .from('sliders')
        .select('*')
        .order('order', { ascending: true })
        .order('created_at', { ascending: false })

    if (error) return { error: error.message }
    return { data }
}

export async function createSlider(data: {
    title: string
    description?: string
    image_url: string
    link?: string
    order?: number
    is_active?: boolean
}) {
    try {
        await assertAdmin()

        const { error } = await supabaseAdmin.from('sliders').insert({
            title: data.title,
            description: data.description,
            image_url: data.image_url,
            link: data.link,
            order: data.order || 0,
            is_active: data.is_active ?? true
        })

        if (error) throw error

        revalidatePath("/dashboard/sliders")
        revalidatePath("/") // Homepage cache update
        return { success: true }
    } catch (error) {
        return { error: (error as Error).message }
    }
}

export async function updateSlider(id: string, data: {
    title: string
    description?: string
    image_url: string
    link?: string
    order?: number
    is_active?: boolean
}) {
    try {
        await assertAdmin()

        const { error } = await supabaseAdmin
            .from('sliders')
            .update({
                title: data.title,
                description: data.description,
                image_url: data.image_url,
                link: data.link,
                order: data.order,
                is_active: data.is_active,
                // updated_at trigger usually handles time, but we don't have it in schema yet, so maybe add later
            })
            .eq('id', id)

        if (error) throw error

        revalidatePath("/dashboard/sliders")
        revalidatePath("/")
        return { success: true }
    } catch (error) {
        return { error: (error as Error).message }
    }
}

export async function deleteSlider(id: string) {
    try {
        await assertAdmin()

        const { error } = await supabaseAdmin
            .from('sliders')
            .delete()
            .eq('id', id)

        if (error) throw error

        revalidatePath("/dashboard/sliders")
        revalidatePath("/")
        return { success: true }
    } catch (error) {
        return { error: (error as Error).message }
    }
}
