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

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    
    // Simple validation
    const audienceType = body.audienceType || 'all';
    const specificUsers = body.specificUsers || '';
    const userSegments = Array.isArray(body.userSegments) ? body.userSegments : [];
    const excludeUnsubscribed = body.excludeUnsubscribed !== false;
    
    let totalCount = 0;
    let users = [];
    
    // Calculate total count based on audience type
    if (audienceType === 'all') {
      totalCount = await prisma.user.count({
        where: {
          userStatus: 'active'
        }
      });

      // Get sample users for preview
      users = await prisma.user.findMany({
        where: {
          userStatus: 'active'
        },
        select: {
          userID: true,
          userEmail: true,
          userFullName: true
        },
        take: 10,
        orderBy: {
          userCreatedDate: 'desc'
        }
      });
    }
    else if (audienceType === 'specific' && specificUsers) {
      const usersList = specificUsers
        .split('\n')
        .map(u => u.trim())
        .filter(Boolean);

      if (usersList.length > 0) {
        users = await prisma.user.findMany({
          where: {
            OR: [
              { userEmail: { in: usersList } },
              { userID: { in: usersList.map(id => parseInt(id)).filter(id => !isNaN(id)) } }
            ]
          },
          select: {
            userID: true,
            userEmail: true,
            userFullName: true
          }
        });
        totalCount = users.length;
      }
    }
    else if (audienceType === 'segmented') {
      // For segmented audience, we'll use a simplified approach
      // In a real implementation, we'd fetch users based on the segments
      if (userSegments.includes('new_users')) {
        // New users calculation - simplified example
        const thirtyDaysAgo = new Date();
        thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
        
        totalCount = await prisma.user.count({
          where: {
            userStatus: 'active',
            userCreatedDate: {
              gte: thirtyDaysAgo
            }
          }
        });
        
        users = await prisma.user.findMany({
          where: {
            userStatus: 'active',
            userCreatedDate: {
              gte: thirtyDaysAgo
            }
          },
          select: {
            userID: true,
            userEmail: true,
            userFullName: true
          },
          take: 10,
          orderBy: {
            userCreatedDate: 'desc'
          }
        });
      } else {
        // Default segment behavior
        totalCount = await prisma.user.count({
          where: {
            userStatus: 'active'
          }
        });
        
        users = await prisma.user.findMany({
          where: {
            userStatus: 'active'
          },
          select: {
            userID: true,
            userEmail: true,
            userFullName: true
          },
          take: 10,
          orderBy: {
            userCreatedDate: 'desc'
          }
        });
      }
    }

    // Format users for response
    const formattedUsers = users.map(user => ({
      id: user.userID,
      name: user.userFullName?.trim() || 'Unknown',
      email: user.userEmail,
      segment: audienceType === 'specific' ? 'Specific User' : 
               audienceType === 'segmented' ? 'Segmented User' : 'All Users'
    }));

    return {
      success: true,
      data: {
        users: formattedUsers,
        totalCount,
        previewCount: formattedUsers.length
      }
    };
  } catch (error) {
    console.error('Error previewing audience:', error);
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to preview audience',
      data: {
        error: error.message
      }
    });
  }
}); 