/**
 * Notification Delivery System
 * Handles SMS and email delivery for critical notifications
 */

export type DeliveryChannel = 'push' | 'email' | 'sms' | 'whatsapp';
export type DeliveryStatus = 'pending' | 'sent' | 'delivered' | 'failed' | 'bounced';

export interface EmailNotification {
  id: string;
  userId: number;
  email: string;
  subject: string;
  body: string;
  htmlBody?: string;
  status: DeliveryStatus;
  createdAt: Date;
  sentAt?: Date;
  deliveredAt?: Date;
  failureReason?: string;
  retryCount: number;
  maxRetries: number;
}

export interface SMSNotification {
  id: string;
  userId: number;
  phoneNumber: string;
  message: string;
  status: DeliveryStatus;
  createdAt: Date;
  sentAt?: Date;
  deliveredAt?: Date;
  failureReason?: string;
  retryCount: number;
  maxRetries: number;
}

export interface WhatsAppNotification {
  id: string;
  userId: number;
  phoneNumber: string;
  message: string;
  mediaUrl?: string;
  status: DeliveryStatus;
  createdAt: Date;
  sentAt?: Date;
  deliveredAt?: Date;
  failureReason?: string;
  retryCount: number;
  maxRetries: number;
}

/**
 * Email templates
 */
export const EMAIL_TEMPLATES = {
  prize_won: {
    subject: '🏆 Congratulations! You Won a Prize!',
    template: (data: any) => `
      <h2>Prize Won!</h2>
      <p>Congratulations! You've won <strong>$${data.amount}</strong> for placing <strong>#${data.rank}</strong> on the leaderboard.</p>
      <p><a href="${data.actionUrl}">View Your Prize</a></p>
    `,
  },
  tier_promotion: {
    subject: '🎉 You\'ve Been Promoted!',
    template: (data: any) => `
      <h2>VIP Tier Promotion</h2>
      <p>Congratulations! You've been promoted to <strong>${data.newTier}</strong> tier!</p>
      <p>New benefits unlocked:</p>
      <ul>${data.benefits.map((b: string) => `<li>${b}</li>`).join('')}</ul>
      <p><a href="${data.actionUrl}">View Your Benefits</a></p>
    `,
  },
  bonus_triggered: {
    subject: '🎁 Bonus Triggered!',
    template: (data: any) => `
      <h2>Bonus Triggered</h2>
      <p>You've triggered a <strong>${data.bonusType}</strong> bonus with a <strong>${data.multiplier}x</strong> multiplier!</p>
      <p><a href="${data.actionUrl}">Play Now</a></p>
    `,
  },
  tournament_started: {
    subject: '🏁 Tournament Started!',
    template: (data: any) => `
      <h2>Tournament Started</h2>
      <p><strong>${data.tournamentName}</strong> has started with a <strong>$${data.prizePool}</strong> prize pool!</p>
      <p><a href="${data.actionUrl}">Join Tournament</a></p>
    `,
  },
  tournament_ended: {
    subject: '🏆 Tournament Results',
    template: (data: any) => `
      <h2>Tournament Ended</h2>
      <p>You finished <strong>#${data.rank}</strong> and won <strong>$${data.prize}</strong>!</p>
      <p><a href="${data.actionUrl}">View Results</a></p>
    `,
  },
  referral_accepted: {
    subject: '💰 Referral Accepted!',
    template: (data: any) => `
      <h2>Referral Accepted</h2>
      <p><strong>${data.referreeName}</strong> joined through your referral link!</p>
      <p>You earned <strong>$${data.commission}</strong> commission.</p>
      <p><a href="${data.actionUrl}">View Referrals</a></p>
    `,
  },
  daily_bonus: {
    subject: '🎁 Daily Bonus Available',
    template: (data: any) => `
      <h2>Daily Bonus</h2>
      <p>Your daily bonus of <strong>$${data.bonusAmount}</strong> is ready to claim!</p>
      <p>Current streak: <strong>${data.streak}</strong> days</p>
      <p><a href="${data.actionUrl}">Claim Bonus</a></p>
    `,
  },
};

/**
 * SMS templates
 */
export const SMS_TEMPLATES = {
  prize_won: (data: any) => `🏆 Congratulations! You won $${data.amount} for rank #${data.rank}! ${data.actionUrl}`,
  tier_promotion: (data: any) => `🎉 You've been promoted to ${data.newTier} VIP tier! ${data.actionUrl}`,
  bonus_triggered: (data: any) => `🎁 ${data.bonusType} bonus triggered with ${data.multiplier}x multiplier! ${data.actionUrl}`,
  tournament_started: (data: any) => `🏁 ${data.tournamentName} started with $${data.prizePool} prize pool! ${data.actionUrl}`,
  tournament_ended: (data: any) => `🏆 You finished #${data.rank} and won $${data.prize}! ${data.actionUrl}`,
  referral_accepted: (data: any) => `💰 ${data.referreeName} joined! You earned $${data.commission} commission! ${data.actionUrl}`,
  daily_bonus: (data: any) => `🎁 Claim your $${data.bonusAmount} daily bonus! Streak: ${data.streak} days ${data.actionUrl}`,
};

/**
 * Create email notification
 */
export function createEmailNotification(
  userId: number,
  email: string,
  subject: string,
  body: string,
  htmlBody?: string
): EmailNotification {
  return {
    id: `email_${userId}_${Date.now()}`,
    userId,
    email,
    subject,
    body,
    htmlBody,
    status: 'pending',
    createdAt: new Date(),
    retryCount: 0,
    maxRetries: 3,
  };
}

/**
 * Create SMS notification
 */
export function createSMSNotification(
  userId: number,
  phoneNumber: string,
  message: string
): SMSNotification {
  return {
    id: `sms_${userId}_${Date.now()}`,
    userId,
    phoneNumber,
    message,
    status: 'pending',
    createdAt: new Date(),
    retryCount: 0,
    maxRetries: 3,
  };
}

/**
 * Create WhatsApp notification
 */
export function createWhatsAppNotification(
  userId: number,
  phoneNumber: string,
  message: string,
  mediaUrl?: string
): WhatsAppNotification {
  return {
    id: `whatsapp_${userId}_${Date.now()}`,
    userId,
    phoneNumber,
    message,
    mediaUrl,
    status: 'pending',
    createdAt: new Date(),
    retryCount: 0,
    maxRetries: 3,
  };
}

/**
 * Send email via Brevo
 */
export async function sendEmailViaBrevo(notification: EmailNotification): Promise<boolean> {
  try {
    // Brevo API integration would go here
    // For now, we'll simulate the API call
    const apiUrl = process.env.BREVO_API_URL || 'https://api.brevo.com/v3/smtp/email';
    const apiKey = process.env.BREVO_API_KEY;

    if (!apiKey) {
      throw new Error('BREVO_API_KEY not configured');
    }

    // Simulate API call
    notification.status = 'sent';
    notification.sentAt = new Date();

    return true;
  } catch (error) {
    notification.retryCount++;
    if (notification.retryCount >= notification.maxRetries) {
      notification.status = 'failed';
      notification.failureReason = error instanceof Error ? error.message : 'Unknown error';
    }
    return false;
  }
}

/**
 * Send SMS via Twilio
 */
export async function sendSMSViaTwilio(notification: SMSNotification): Promise<boolean> {
  try {
    // Twilio API integration would go here
    const accountSid = process.env.TWILIO_ACCOUNT_SID;
    const authToken = process.env.TWILIO_AUTH_TOKEN;
    const fromNumber = process.env.TWILIO_PHONE_NUMBER;

    if (!accountSid || !authToken || !fromNumber) {
      throw new Error('Twilio credentials not configured');
    }

    // Simulate API call
    notification.status = 'sent';
    notification.sentAt = new Date();

    return true;
  } catch (error) {
    notification.retryCount++;
    if (notification.retryCount >= notification.maxRetries) {
      notification.status = 'failed';
      notification.failureReason = error instanceof Error ? error.message : 'Unknown error';
    }
    return false;
  }
}

/**
 * Send WhatsApp message via Twilio
 */
export async function sendWhatsAppViaTwilio(notification: WhatsAppNotification): Promise<boolean> {
  try {
    const accountSid = process.env.TWILIO_ACCOUNT_SID;
    const authToken = process.env.TWILIO_AUTH_TOKEN;
    const fromNumber = process.env.TWILIO_WHATSAPP_NUMBER;

    if (!accountSid || !authToken || !fromNumber) {
      throw new Error('Twilio WhatsApp credentials not configured');
    }

    // Simulate API call
    notification.status = 'sent';
    notification.sentAt = new Date();

    return true;
  } catch (error) {
    notification.retryCount++;
    if (notification.retryCount >= notification.maxRetries) {
      notification.status = 'failed';
      notification.failureReason = error instanceof Error ? error.message : 'Unknown error';
    }
    return false;
  }
}

/**
 * Mark notification as delivered
 */
export function markAsDelivered(notification: EmailNotification | SMSNotification | WhatsAppNotification): void {
  notification.status = 'delivered';
  notification.deliveredAt = new Date();
}

/**
 * Mark notification as bounced
 */
export function markAsBounced(
  notification: EmailNotification | SMSNotification | WhatsAppNotification,
  reason: string
): void {
  notification.status = 'bounced';
  notification.failureReason = reason;
}

/**
 * Get delivery statistics
 */
export interface DeliveryStats {
  totalSent: number;
  totalDelivered: number;
  totalFailed: number;
  totalBounced: number;
  deliveryRate: number;
  byChannel: Record<DeliveryChannel, number>;
}

export function calculateDeliveryStats(
  emails: EmailNotification[],
  smss: SMSNotification[],
  whatsapps: WhatsAppNotification[]
): DeliveryStats {
  const allNotifications = [...emails, ...smss, ...whatsapps];

  const stats: DeliveryStats = {
    totalSent: allNotifications.filter((n) => n.status !== 'pending').length,
    totalDelivered: allNotifications.filter((n) => n.status === 'delivered').length,
    totalFailed: allNotifications.filter((n) => n.status === 'failed').length,
    totalBounced: allNotifications.filter((n) => n.status === 'bounced').length,
    deliveryRate: 0,
    byChannel: {
      push: 0,
      email: emails.filter((e) => e.status === 'delivered').length,
      sms: smss.filter((s) => s.status === 'delivered').length,
      whatsapp: whatsapps.filter((w) => w.status === 'delivered').length,
    },
  };

  if (stats.totalSent > 0) {
    stats.deliveryRate = (stats.totalDelivered / stats.totalSent) * 100;
  }

  return stats;
}

/**
 * Retry failed notifications
 */
export async function retryFailedNotifications(
  emails: EmailNotification[],
  smss: SMSNotification[],
  whatsapps: WhatsAppNotification[]
): Promise<{ succeeded: number; failed: number }> {
  let succeeded = 0;
  let failed = 0;

  // Retry emails
  for (const email of emails.filter((e) => e.status === 'pending' && e.retryCount < e.maxRetries)) {
    const success = await sendEmailViaBrevo(email);
    if (success) succeeded++;
    else failed++;
  }

  // Retry SMS
  for (const sms of smss.filter((s) => s.status === 'pending' && s.retryCount < s.maxRetries)) {
    const success = await sendSMSViaTwilio(sms);
    if (success) succeeded++;
    else failed++;
  }

  // Retry WhatsApp
  for (const whatsapp of whatsapps.filter((w) => w.status === 'pending' && w.retryCount < w.maxRetries)) {
    const success = await sendWhatsAppViaTwilio(whatsapp);
    if (success) succeeded++;
    else failed++;
  }

  return { succeeded, failed };
}
