"use server"

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

export interface SmsTemplate {
    id: string
    title: string
    message: string
    created_at: string
}

export async function getTemplates() {
    try {
        const supabase = createClient()
        const { data, error } = await supabase
            .from('sms_templates')
            .select('*')
            .order('created_at', { ascending: false })

        if (error) throw error
        return { success: true, data: data as SmsTemplate[] }
    } catch (error) {
        return { success: false, error: (error as Error).message }
    }
}

export async function createTemplate(title: string, message: string) {
    try {
        const supabase = createClient()
        const { error } = await supabase
            .from('sms_templates')
            .insert({ title, message })

        if (error) throw error
        revalidatePath('/dashboard/sms')
        return { success: true }
    } catch (error) {
        return { success: false, error: (error as Error).message }
    }
}

export async function deleteTemplate(id: string) {
    try {
        const supabase = createClient()
        const { error } = await supabase
            .from('sms_templates')
            .delete()
            .eq('id', id)

        if (error) throw error
        revalidatePath('/dashboard/sms')
        return { success: true }
    } catch (error) {
        return { success: false, error: (error as Error).message }
    }
}
