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

export default defineEventHandler(async (event) => {
  try {
    const id = event.context.params.id;
    const body = await readBody(event);

    // Validate if notification exists
    const existingNotification = await prisma.notifications.findUnique({
      where: { id },
      include: {
        notification_channels: true,
        notification_user_segments: true
      }
    });

    if (!existingNotification) {
      throw createError({
        statusCode: 404,
        statusMessage: 'Notification not found'
      });
    }

    // Prepare update data
    const updateData = {
      title: body.title,
      type: body.type,
      priority: body.priority,
      category_id: body.category_id,
      status: body.status,
      delivery_type: body.delivery_type,
      scheduled_at: body.scheduled_at ? new Date(body.scheduled_at) : undefined,
      timezone: body.timezone,
      expires_at: body.expires_at ? new Date(body.expires_at) : undefined,
      enable_ab_testing: body.enable_ab_testing,
      ab_test_split: body.ab_test_split,
      ab_test_name: body.ab_test_name,
      enable_tracking: body.enable_tracking,
      audience_type: body.audience_type,
      specific_users: body.specific_users,
      user_status: body.user_status,
      registration_period: body.registration_period,
      exclude_unsubscribed: body.exclude_unsubscribed,
      respect_do_not_disturb: body.respect_do_not_disturb,
      content_type: body.content_type,
      template_id: body.template_id,
      email_subject: body.email_subject,
      email_content: body.email_content,
      call_to_action_text: body.call_to_action_text,
      call_to_action_url: body.call_to_action_url,
      push_title: body.push_title,
      push_body: body.push_body,
      push_image_url: body.push_image_url,
      estimated_reach: body.estimated_reach,
      updated_at: new Date()
    };

    // Remove undefined values
    Object.keys(updateData).forEach(key => 
      updateData[key] === undefined && delete updateData[key]
    );

    // Start transaction
    const updatedNotification = await prisma.$transaction(async (tx) => {
      // Update notification
      const notification = await tx.notifications.update({
        where: { id },
        data: updateData,
        include: {
          notification_channels: true,
          notification_categories: true,
          notification_templates: true,
          notification_user_segments: {
            include: {
              user_segments: true
            }
          }
        }
      });

      // Update channels if provided
      if (Array.isArray(body.channels)) {
        // Validate channel data structure
        const invalidChannels = body.channels.filter(channel => !channel.type);
        if (invalidChannels.length > 0) {
          throw createError({
            statusCode: 400,
            statusMessage: 'Invalid channel data',
            data: {
              error: 'Each channel must have a type property',
              invalidChannels,
              receivedChannels: body.channels
            }
          });
        }

        // Delete existing channels
        await tx.notification_channels.deleteMany({
          where: { notification_id: id }
        });

        // Create new channels
        if (body.channels.length > 0) {
          await tx.notification_channels.createMany({
            data: body.channels.map(channel => ({
              notification_id: id,
              channel_type: channel.type,
              is_enabled: channel.is_enabled !== false
            }))
          });
        }
      }

      // Update user segments if provided
      if (Array.isArray(body.user_segments)) {
        // Delete existing segments
        await tx.notification_user_segments.deleteMany({
          where: { notification_id: id }
        });

        // Create new segments
        if (body.user_segments.length > 0) {
          await tx.notification_user_segments.createMany({
            data: body.user_segments.map(segmentId => ({
              notification_id: id,
              segment_id: segmentId
            }))
          });
        }
      }

      return notification;
    });

    return {
      success: true,
      data: updatedNotification
    };

  } catch (error) {
    console.error('Error updating notification:', error);
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.statusMessage || 'Failed to update notification',
      data: {
        error: error.message
      }
    });
  }
}); 