import { z } from "zod"; import prisma from "~/server/utils/prisma"; // Validation schema for batch creation const createBatchSchema = z.object({ name: z.string().min(1, "Batch name is required"), type: z.string().min(1, "Message type is required"), description: z.string().optional(), priority: z.string().default("medium"), template: z.string().optional(), segment: z.string().optional(), scheduledAt: z.string().optional(), }); export default defineEventHandler(async (event) => { try { // Parse and validate request body const body = await readBody(event); const batchData = createBatchSchema.parse(body); // Create a new batch notification const newBatch = await prisma.notifications.create({ data: { title: batchData.name, type: batchData.type, priority: batchData.priority, delivery_type: "batch", status: batchData.scheduledAt ? "scheduled" : "draft", scheduled_at: batchData.scheduledAt ? new Date(batchData.scheduledAt) : null, audience_type: batchData.segment ? "segment" : "all", content_type: "template", template_id: batchData.template || null, created_by: "system", // In a real application, this would be the user ID created_at: new Date(), updated_at: new Date(), }, }); // If a segment is specified, create the segment association if (batchData.segment) { await prisma.notification_user_segments.create({ data: { notification_id: newBatch.id, segment_id: batchData.segment, created_at: new Date(), }, }); } // Log the batch creation await prisma.notification_logs.create({ data: { notification_id: newBatch.id, action: "Batch Created", actor_id: "system", // In a real application, this would be the user ID status: newBatch.status, details: `Batch notification "${batchData.name}" created`, created_at: new Date(), }, }); return { success: true, data: { id: newBatch.id, name: newBatch.title, status: newBatch.status, message: "Batch created successfully", }, }; } catch (error) { console.error("Error creating batch:", error); // Handle validation errors if (error.name === "ZodError") { throw createError({ statusCode: 400, statusMessage: "Invalid batch data", data: { errors: error.errors, }, }); } if (error.statusCode) { throw error; } throw createError({ statusCode: 500, statusMessage: "Failed to create batch", data: { error: error.message, }, }); } finally { } });