"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
        }
    }
)

export async function createCategory(data: { name: string, description?: string, image_url?: string }) {
    const supabase = createClient()

    // Check admin
    const { data: { user } } = await supabase.auth.getUser()
    if (!user) return { error: "Oturum açmanız gerekiyor." }

    // Check if current user is admin
    const { data: profile } = await supabase.from('profiles').select('role').eq('id', user.id).single()
    if (profile?.role !== 'admin') return { error: "Yetkisiz işlem." }

    // Generate slug from name
    const slug = data.name.toLowerCase()
        .replace(/ğ/g, 'g')
        .replace(/ü/g, 'u')
        .replace(/ş/g, 's')
        .replace(/ı/g, 'i')
        .replace(/ö/g, 'o')
        .replace(/ç/g, 'c')
        .replace(/[^a-z0-9]/g, '-')
        .replace(/-+/g, '-')
        .replace(/^-|-$/g, '')

    const { error } = await supabaseAdmin.from('categories').insert({
        name: data.name,
        slug: slug,
        description: data.description,
        image_url: data.image_url
    })

    if (error) return { error: "Kategori oluşturulamadı: " + error.message }

    revalidatePath("/dashboard/categories")
    return { success: true }
}

export async function updateCategory(id: string, data: { name: string, description?: string, image_url?: string }) {
    const supabase = createClient()

    // Check admin
    const { data: { user } } = await supabase.auth.getUser()
    if (!user) return { error: "Oturum açmanız gerekiyor." }

    // Check if current user is admin
    const { data: profile } = await supabase.from('profiles').select('role').eq('id', user.id).single()
    if (profile?.role !== 'admin') return { error: "Yetkisiz işlem." }

    const slug = data.name.toLowerCase()
        .replace(/ğ/g, 'g')
        .replace(/ü/g, 'u')
        .replace(/ş/g, 's')
        .replace(/ı/g, 'i')
        .replace(/ö/g, 'o')
        .replace(/ç/g, 'c')
        .replace(/[^a-z0-9]/g, '-')
        .replace(/-+/g, '-')
        .replace(/^-|-$/g, '')

    const { error } = await supabaseAdmin.from('categories').update({
        name: data.name,
        slug: slug,
        description: data.description,
        image_url: data.image_url
    }).eq('id', id)

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

    revalidatePath("/dashboard/categories")
    return { success: true }
}

export async function deleteCategory(id: string) {
    const supabase = createClient()

    // Check admin
    const { data: { user } } = await supabase.auth.getUser()
    if (!user) return { error: "Oturum açmanız gerekiyor." }

    // Check if current user is admin
    const { data: profile } = await supabase.from('profiles').select('role').eq('id', user.id).single()
    if (profile?.role !== 'admin') return { error: "Yetkisiz işlem." }

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

    if (error) return { error: "Kategori silinemedi: " + error.message }

    revalidatePath("/dashboard/categories")
    return { success: true }
}
