import { NextResponse } from 'next/server'; import { dataService } from '@/lib/data-service'; import { TEMPLATE_CATEGORIES } from '@/lib/templates-service'; export async function GET(request: Request) { try { const { searchParams } = new URL(request.url); const id = searchParams.get('id'); const category = searchParams.get('category'); if (id) { const template = dataService.getMessageTemplateById(id); if (!template) { return NextResponse.json({ success: false, error: 'Plantilla no encontrada' }, { status: 404 }); } return NextResponse.json({ success: true, template }); } const templates = dataService.getMessageTemplates(category || undefined); return NextResponse.json({ success: true, templates, categories: TEMPLATE_CATEGORIES, total: templates.length, }); } catch (error: any) { return NextResponse.json({ success: false, error: error.message }, { status: 500 }); } } export async function PUT(request: Request) { try { const body = await request.json(); const { id, content, isActive, title, description } = body; if (!id) { return NextResponse.json({ success: false, error: 'ID de la plantilla es obligatorio' }, { status: 400 }); } const updated = dataService.updateMessageTemplate(id, { ...(content !== undefined && { content }), ...(isActive !== undefined && { isActive }), ...(title !== undefined && { title }), ...(description !== undefined && { description }), }); if (!updated) { return NextResponse.json({ success: false, error: 'Plantilla no encontrada' }, { status: 404 }); } return NextResponse.json({ success: true, template: updated, message: `Plantilla "${updated.title}" actualizada correctamente.`, }); } catch (error: any) { return NextResponse.json({ success: false, error: error.message }, { status: 400 }); } } export async function POST(request: Request) { try { const body = await request.json(); const { action, id, templateId, variables } = body; if (action === 'reset' && id) { const restored = dataService.resetMessageTemplate(id); if (!restored) { return NextResponse.json({ success: false, error: 'Plantilla no encontrada' }, { status: 404 }); } return NextResponse.json({ success: true, template: restored, message: `Plantilla "${restored.title}" restaurada al texto predeterminado de fábrica.`, }); } if (action === 'reset_all') { const templates = dataService.resetAllMessageTemplates(); return NextResponse.json({ success: true, templates, message: 'Todas las plantillas han sido restauradas a sus textos predeterminados de fábrica.', }); } if (action === 'render' && templateId) { const rendered = dataService.renderMessageTemplate(templateId, variables || {}); return NextResponse.json({ success: true, renderedText: rendered, }); } return NextResponse.json({ success: false, error: 'Acción no válida' }, { status: 400 }); } catch (error: any) { return NextResponse.json({ success: false, error: error.message }, { status: 400 }); } }