"use server"

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

// Admin client for privileged operations (accessing sms_settings)
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 getSmsSettings() {
    try {
        await assertAdmin()

        const { data, error } = await supabaseAdmin
            .from('sms_settings')
            .select('*')
            .single()

        if (error && error.code !== 'PGRST116') { // PGRST116 is 'not found', which is fine initially
            throw error
        }

        return { data }
    } catch (error) {
        return { error: (error as Error).message }
    }
}

export async function updateSmsSettings(data: {
    username: string
    password?: string // Optional if not changing
    header: string
}) {
    try {
        await assertAdmin()

        // Check if exists
        const { data: existing } = await supabaseAdmin.from('sms_settings').select('id').single()

        const updates: {
            username: string
            header: string
            updated_at: string
            password?: string
        } = {
            username: data.username,
            header: data.header,
            updated_at: new Date().toISOString()
        }

        // Only update password if provided
        if (data.password && data.password.trim() !== '') {
            updates.password = data.password
        }

        if (existing) {
            const { error } = await supabaseAdmin
                .from('sms_settings')
                .update(updates)
                .eq('id', existing.id)
            if (error) throw error
        } else {
            // First time setup, password is mandatory if not exists, but we can't easily check 'locally'
            // We assume if new, password must be in updates.
            if (!data.password) throw new Error("Yeni kurulum için şifre gereklidir.")

            const { error } = await supabaseAdmin
                .from('sms_settings')
                .insert({ ...updates, password: data.password })
            if (error) throw error
        }

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

    } catch (error) {
        return { error: (error as Error).message }
    }
}

export async function sendTestSms(phone: string) {
    try {
        await assertAdmin()

        // Fetch credentials
        const { data: settings } = await supabaseAdmin.from('sms_settings').select('*').single()
        if (!settings) throw new Error("SMS ayarları yapılmamış.")

        const mobileService = new NetGsmService({
            username: settings.username,
            password: settings.password,
            header: settings.header,
            apiUrl: settings.api_url
        })

        const result = await mobileService.sendSms(phone, "ParaKasa Test SMS: Entegrasyon basarili.")

        // Log the result
        await supabaseAdmin.from('sms_logs').insert({
            phone,
            message: "ParaKasa Test SMS: Entegrasyon basarili.",
            status: result.success ? 'success' : 'error',
            response_code: result.code || result.error
        })

        if (!result.success) {
            throw new Error(result.error || "SMS gönderilemedi.")
        }

        return { success: true, jobId: result.jobId }

    } catch (error) {
        return { error: (error as Error).message }
    }
}

export async function sendBulkSms(phones: string[], message: string) {
    try {
        await assertAdmin()

        // Fetch credentials
        const { data: settings } = await supabaseAdmin.from('sms_settings').select('*').single()
        if (!settings) throw new Error("SMS ayarları yapılmamış.")

        const mobileService = new NetGsmService({
            username: settings.username,
            password: settings.password,
            header: settings.header,
            apiUrl: settings.api_url
        })

        // Remove duplicates and empty
        const uniquePhones = Array.from(new Set(phones.filter(p => p && p.trim() !== '')))

        const results = []

        for (const phone of uniquePhones) {
            const result = await mobileService.sendSms(phone, message)

            // Log result
            await supabaseAdmin.from('sms_logs').insert({
                phone,
                message,
                status: result.success ? 'success' : 'error',
                response_code: result.code || result.error
            })

            results.push({ phone, ...result })
        }

        const successCount = results.filter(r => r.success).length
        const total = uniquePhones.length

        revalidatePath("/dashboard/sms")
        return {
            success: true,
            message: `${total} kişiden ${successCount} kişiye başarıyla gönderildi.`,
            details: results
        }

    } catch (error) {
        return { error: (error as Error).message }
    }
}

export async function getSmsLogs(limit: number = 50) {
    try {
        await assertAdmin()

        const { data, error } = await supabaseAdmin
            .from('sms_logs')
            .select('*')
            .order('created_at', { ascending: false })
            .limit(limit)

        if (error) throw error

        return { success: true, data }
    } catch (error) {
        return { error: (error as Error).message }
    }
}
