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

export default defineEventHandler(async (event) => {
  try {
    // Get current user from auth middleware
    const user = event.context.user;
    if (!user) {
      throw createError({
        statusCode: 401,
        statusMessage: "Authentication required",
      });
    }

    // Get delivery statistics from the last 30 days
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

    // Get email statistics
    const emailStats = await prisma.notification_delivery.groupBy({
      by: ['is_success'],
      where: {
        channel_type: 'email',
        created_at: {
          gte: thirtyDaysAgo
        }
      },
      _count: {
        id: true
      }
    });

    // Get push notification statistics
    const pushStats = await prisma.notification_delivery.groupBy({
      by: ['is_success'],
      where: {
        channel_type: 'push',
        created_at: {
          gte: thirtyDaysAgo
        }
      },
      _count: {
        id: true
      }
    });

    // Calculate totals
    const emailCount = emailStats.reduce((sum, stat) => sum + stat._count.id, 0);
    const pushCount = pushStats.reduce((sum, stat) => sum + stat._count.id, 0);
    const emailSuccess = emailStats.find(stat => stat.is_success)?._count.id || 0;
    const pushSuccess = pushStats.find(stat => stat.is_success)?._count.id || 0;

    // Calculate success rate
    const totalDeliveries = emailCount + pushCount;
    const totalSuccessful = emailSuccess + pushSuccess;
    const successRate = totalDeliveries > 0 
      ? (totalSuccessful / totalDeliveries) * 100 
      : 100;

    return {
      success: true,
      data: {
        emailsSent: emailCount,
        pushSent: pushCount,
        successRate: Number(successRate.toFixed(2)),
        failed: totalDeliveries - totalSuccessful
      }
    };
  } catch (error) {
    console.error('Error fetching delivery stats:', {
      message: error.message,
      code: error.code,
      meta: error.meta,
      stack: error.stack
    });
    
    if (error.statusCode) {
      throw error;
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: `Failed to fetch delivery statistics: ${error.message}`
    });
  }
}); 