import { z } from "zod";
import prisma from "~/server/utils/prisma";

// Query parameter validation schema
const batchQuerySchema = z.object({
  page: z
    .string()
    .transform((val) => parseInt(val) || 1)
    .optional(),
  limit: z
    .string()
    .transform((val) => parseInt(val) || 10)
    .optional(),
  status: z.string().optional(),
});

export default defineEventHandler(async (event) => {
  try {
    // Parse and validate query parameters
    const queryParams = getQuery(event) || {};
    const params = batchQuerySchema.parse(queryParams);

    // Build where clause for filtering
    const where = {
      delivery_type: "batch", // Identify batch notifications
    };

    if (params.status) {
      where.status = params.status;
    }

    // Get total count for pagination
    const total = await prisma.notifications.count({ where });

    // Calculate pagination metadata
    const totalPages = Math.ceil(total / params.limit);

    // Fetch batch notifications with related data
    const batches = await prisma.notifications.findMany({
      where,
      select: {
        id: true,
        title: true,
        status: true,
        scheduled_at: true,
        created_at: true,
        priority: true,
        notification_recipients: {
          select: {
            id: true,
            status: true,
          },
        },
        notification_queue: {
          select: {
            id: true,
            status: true,
          },
        },
      },
      orderBy: {
        created_at: "desc",
      },
      skip: (params.page - 1) * params.limit,
      take: params.limit,
    });

    // Format batches for response
    const formattedBatches = batches.map((batch) => {
      // Calculate progress
      const totalRecipients = batch.notification_recipients.length;
      const processed = batch.notification_recipients.filter(
        (r) => r.status === "sent" || r.status === "delivered"
      ).length;

      // Map status to UI-friendly status
      let status = batch.status;
      if (status === "draft") status = "draft";
      else if (status === "scheduled") status = "scheduled";
      else if (status === "processing") status = "sending";
      else if (status === "completed") status = "sent";

      return {
        id: batch.id,
        name: batch.title,
        description: `Batch notification with ${totalRecipients} recipients`,
        status: status,
        processed: processed,
        total: totalRecipients,
        time: batch.created_at,
      };
    });

    return {
      success: true,
      data: {
        batches: formattedBatches,
        pagination: {
          page: params.page,
          totalPages,
          total,
          hasMore: params.page < totalPages,
        },
      },
    };
  } catch (error) {
    console.error("Error fetching batches:", error);

    if (error.statusCode) {
      throw error;
    }

    throw createError({
      statusCode: 500,
      statusMessage: "Failed to fetch batch notifications",
      data: {
        error: error.message,
      },
    });
  } finally {
  }
}); 