"use server"

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

// WARNING: specialized client for admin actions only
// This requires SUPABASE_SERVICE_ROLE_KEY to be set in .env.local
const supabaseAdmin = createSupabaseClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.SUPABASE_SERVICE_ROLE_KEY!,
    {
        auth: {
            autoRefreshToken: false,
            persistSession: false
        }
    }
)

export async function createUser(firstName: string, lastName: string, email: string, password: string, role: 'admin' | 'user', phone?: string) {

    // 1. Check if current user is admin
    try {
        await assertAdmin()
    } catch (error) {
        return { error: (error as Error).message }
    }

    // 2. Create user using Admin client
    const { data: newUser, error: createError } = await supabaseAdmin.auth.admin.createUser({
        email,
        password,
        email_confirm: true, // Auto confirm
        user_metadata: {
            full_name: `${firstName} ${lastName}`.trim()
        }
    })

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

    if (!newUser.user) {
        return { error: "Kullanıcı oluşturulamadı." }
    }

    // 3. Create profile entry (if not handled by trigger, but we'll do it manually to be safe/explicit about role)
    const { error: profileError } = await supabaseAdmin
        .from('profiles')
        .insert({
            id: newUser.user.id,
            full_name: `${firstName} ${lastName}`.trim(),
            role: role,
            phone: phone
        })

    if (profileError) {
        // Optional: delete auth user if profile creation fails? 
        // For now just return error
        return { error: "Kullanıcı oluşturuldu ancak profil kaydedilemedi: " + profileError.message }
    }

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

export async function deleteUser(userId: string) {

    // Check admin
    try {
        await assertAdmin()
    } catch (error) {
        return { error: (error as Error).message }
    }

    // Delete user
    const { error } = await supabaseAdmin.auth.admin.deleteUser(userId)

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

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

export async function updateUser(userId: string, data: { firstName: string, lastName: string, email: string, password?: string, role: 'admin' | 'user', phone?: string }) {

    // Check admin
    try {
        await assertAdmin()
    } catch (error) {
        return { error: (error as Error).message }
    }

    // 1. Update Profile (Role and Name)
    const { error: profileError } = await supabaseAdmin
        .from('profiles')
        .update({
            full_name: `${data.firstName} ${data.lastName}`.trim(),
            role: data.role,
            phone: data.phone
        })
        .eq('id', userId)

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

    // 2. Update Auth (Email and Password)
    const authUpdates: { email: string; user_metadata: { full_name: string }; password?: string } = {
        email: data.email,
        user_metadata: {
            full_name: `${data.firstName} ${data.lastName}`.trim()
        }
    }
    if (data.password && data.password.length >= 6) {
        authUpdates.password = data.password
    }

    const { error: authError } = await supabaseAdmin.auth.admin.updateUserById(userId, authUpdates)

    if (authError) return { error: "Kullanıcı giriş bilgileri güncellenemedi: " + authError.message }

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

export async function updateProfile(data: { firstName: string, lastName: string, phone?: string }) {
    const supabase = createClient()
    const { data: { user } } = await supabase.auth.getUser()

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

    const { error } = await supabase
        .from('profiles')
        .update({
            full_name: `${data.firstName} ${data.lastName}`.trim(),
            phone: data.phone
        })
        .eq('id', user.id)

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

    // Update Auth Metadata as well
    if (data.firstName || data.lastName) {
        await supabase.auth.updateUser({
            data: {
                full_name: `${data.firstName} ${data.lastName}`.trim()
            }
        })
    }

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

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

    const { data: profile } = await supabase
        .from('profiles')
        .select('role')
        .eq('id', currentUser.id)
        .single()

    if (!profile || profile.role !== 'admin') {
        throw new Error("Yetkisiz işlem. Sadece yöneticiler bu işlemi gerçekleştirebilir.")
    }

    return currentUser
}
