'use server'; import { db } from '@/lib/db'; import { revalidatePath } from 'next/cache'; export async function getPrompts(params?: { category?: string; query?: string }) { try { const where: any = {}; if (params?.category) { where.category = params.category; } if (params?.query && params.query.trim()) { const q = params.query.trim(); where.OR = [ { title: { contains: q, mode: 'insensitive' } }, { description: { contains: q, mode: 'insensitive' } }, { content: { contains: q, mode: 'insensitive' } }, { tags: { hasSome: [q] } }, ]; } const prompts = await db.prompt.findMany({ where, orderBy: { createdAt: 'desc', }, }); return prompts; } catch (error) { console.error('Error fetching prompts:', error); return []; } } export async function getPromptBySlug(slug: string) { try { const prompt = await db.prompt.findUnique({ where: { slug }, }); return prompt; } catch (error) { console.error('Error fetching prompt by slug:', error); return null; } } export async function createPrompt(data: { title: string; category: string; description: string; content: string; tags?: string[]; isOpen?: boolean; }) { try { const slug = data.title .toLowerCase() .trim() .replace(/[^\w\s-]/g, '') .replace(/[\s_-]+/g, '-') + '-' + Date.now().toString().slice(-4); const tags = data.tags && data.tags.length > 0 ? data.tags : [data.category, 'AI', 'Prompt']; const newPrompt = await db.prompt.create({ data: { title: data.title, slug, category: data.category, description: data.description, content: data.content, tags, isOpen: data.isOpen ?? false, }, }); revalidatePath('/[locale]/admin'); return { success: true, prompt: newPrompt }; } catch (error: any) { console.error('Error creating prompt:', error); return { success: false, error: error.message || 'Failed to create prompt' }; } } export async function updatePrompt(id: string, data: { title: string; category: string; description: string; content: string; tags?: string[]; isOpen?: boolean; }) { try { const tags = data.tags && data.tags.length > 0 ? data.tags : [data.category, 'AI', 'Prompt']; const updated = await db.prompt.update({ where: { id }, data: { title: data.title, category: data.category, description: data.description, content: data.content, tags, isOpen: data.isOpen ?? false, updatedAt: new Date(), }, }); revalidatePath('/[locale]/admin'); return { success: true, prompt: updated }; } catch (error: any) { console.error('Error updating prompt:', error); return { success: false, error: error.message || 'Failed to update prompt' }; } } export async function deletePrompt(id: string) { try { await db.prompt.delete({ where: { id }, }); revalidatePath('/[locale]/admin'); return { success: true }; } catch (error: any) { console.error('Error deleting prompt:', error); return { success: false, error: error.message || 'Failed to delete prompt' };; } }