import { invokeLLM } from "./_core/llm.ts";
import { notifyOwner } from "./_core/notification.ts";

/**
 * Send email notification using Manus built-in email service
 */
export async function sendEmailNotification(
  email: string,
  subject: string,
  message: string,
  data?: any
): Promise<boolean> {
  try {
    // Use the built-in notification API to send email
    const result = await notifyOwner({
      title: subject,
      content: `${message}\n\nData: ${JSON.stringify(data || {})}`,
    });
    return result;
  } catch (err: any) {
    console.error("[Email Notification] Failed:", err.message);
    return false;
  }
}

/**
 * Send push notification using Manus built-in push service
 * In production, this would integrate with a push notification service like Firebase Cloud Messaging
 */
export async function sendPushNotification(
  userId: number,
  title: string,
  message: string,
  data?: any
): Promise<boolean> {
  try {
    // For now, we log the push notification
    // In production, integrate with FCM or similar service
    console.log(`[Push Notification] User ${userId}: ${title} - ${message}`);
    
    // You can extend this to call an external push service
    // Example: Firebase Cloud Messaging, OneSignal, etc.
    
    return true;
  } catch (err: any) {
    console.error("[Push Notification] Failed:", err.message);
    return false;
  }
}

/**
 * Send SMS notification (optional)
 */
export async function sendSmsNotification(
  phoneNumber: string,
  message: string
): Promise<boolean> {
  try {
    // In production, integrate with Twilio, AWS SNS, or similar
    console.log(`[SMS Notification] ${phoneNumber}: ${message}`);
    return true;
  } catch (err: any) {
    console.error("[SMS Notification] Failed:", err.message);
    return false;
  }
}

/**
 * Send in-app notification (already handled by database)
 */
export async function sendInAppNotification(
  userId: number,
  title: string,
  message: string,
  data?: any
): Promise<boolean> {
  try {
    // In-app notifications are stored in the database
    // This is just a placeholder for consistency
    console.log(`[In-App Notification] User ${userId}: ${title}`);
    return true;
  } catch (err: any) {
    console.error("[In-App Notification] Failed:", err.message);
    return false;
  }
}

/**
 * Process notification channels and send via appropriate services
 */
export async function processNotificationChannels(
  userId: number,
  userEmail: string,
  channels: string[],
  title: string,
  message: string,
  data?: any
): Promise<void> {
  for (const channel of channels) {
    try {
      switch (channel) {
        case "email":
          await sendEmailNotification(userEmail, title, message, data);
          break;
        case "push":
          await sendPushNotification(userId, title, message, data);
          break;
        case "sms":
          // SMS would require phone number from user profile
          // await sendSmsNotification(userPhone, message);
          break;
        case "in_app":
          await sendInAppNotification(userId, title, message, data);
          break;
      }
    } catch (err: any) {
      console.error(`[Notification] Failed to send via ${channel}:`, err.message);
    }
  }
}

/**
 * Generate email HTML template for notifications
 */
export function generateEmailTemplate(
  title: string,
  message: string,
  actionUrl?: string,
  actionText?: string
): string {
  return `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background-color: #f5f5f5; }
    .container { max-width: 600px; margin: 0 auto; background-color: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
    .header { background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%); padding: 24px; text-align: center; }
    .header h1 { color: #1a1a1a; margin: 0; font-size: 24px; }
    .content { padding: 24px; }
    .content p { color: #333; line-height: 1.6; margin: 0 0 16px 0; }
    .action { text-align: center; margin: 24px 0; }
    .action a { display: inline-block; background-color: #ffd700; color: #1a1a1a; padding: 12px 24px; border-radius: 4px; text-decoration: none; font-weight: bold; }
    .footer { background-color: #f9f9f9; padding: 16px; text-align: center; color: #999; font-size: 12px; border-top: 1px solid #eee; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>${title}</h1>
    </div>
    <div class="content">
      <p>${message}</p>
      ${actionUrl && actionText ? `<div class="action"><a href="${actionUrl}">${actionText}</a></div>` : ""}
    </div>
    <div class="footer">
      <p>CoinKrazy.com — Sweepstakes Social Casino</p>
      <p>© 2026 All rights reserved</p>
    </div>
  </div>
</body>
</html>
  `;
}
