'use server';

import { prisma } from './prisma';
import { revalidatePath } from 'next/cache';

export async function createBearrLink(formData: FormData) {
    const payload = {
        kategori: formData.get('kategori') as string,
        judul: formData.get('judul') as string,
        deskripsi: (formData.get('deskripsi') as string) || null,
        url: formData.get('url') as string,
        tipe_url: formData.get('tipe_url') as string,
        is_active: formData.get('is_active') === 'true',
        urutan: parseInt(formData.get('urutan') as string) || 0,
    };

    if (!payload.kategori || !payload.judul || !payload.url) {
        return { error: 'Kategori, Judul, dan URL wajib diisi.' };
    }

    try {
        await prisma.bearrLink.create({ data: payload });
        revalidatePath('/bearr');
        revalidatePath('/admin/bearr');
    } catch (e: any) {
        return { error: e.message };
    }
}

export async function updateBearrLink(id: string, formData: FormData) {
    const payload = {
        kategori: formData.get('kategori') as string,
        judul: formData.get('judul') as string,
        deskripsi: (formData.get('deskripsi') as string) || null,
        url: formData.get('url') as string,
        tipe_url: formData.get('tipe_url') as string,
        is_active: formData.get('is_active') === 'true',
        urutan: parseInt(formData.get('urutan') as string) || 0,
    };

    try {
        await prisma.bearrLink.update({ where: { id }, data: payload });
        revalidatePath('/bearr');
        revalidatePath('/admin/bearr');
    } catch (e: any) {
        return { error: e.message };
    }
}

export async function deleteBearrLink(id: string) {
    try {
        await prisma.bearrLink.delete({ where: { id } });
        revalidatePath('/bearr');
        revalidatePath('/admin/bearr');
    } catch (e: any) {
        return { error: e.message };
    }
}
