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

export interface EmailTemplate {
  subject: string;
  html: string;
  text: string;
}

/**
 * Email Service
 * Handles transactional emails for the platform
 */

export async function generateWinNotificationEmail(
  userName: string,
  gameName: string,
  winAmount: number,
  totalBalance: number
): Promise<EmailTemplate> {
  const response = await invokeLLM({
    messages: [
      {
        role: "system",
        content: `You are an email template generator for CoinKrazy casino. Generate professional, engaging HTML emails.
        Always include the CoinKrazy branding and keep emails mobile-friendly.
        Return ONLY valid HTML (no markdown, no code blocks).`,
      },
      {
        role: "user",
        content: `Generate an HTML email for a player who just won at our casino.
        Player name: ${userName}
        Game: ${gameName}
        Win amount: $${winAmount.toFixed(2)}
        New balance: $${totalBalance.toFixed(2)}
        
        Make it celebratory and include a call-to-action to play more games.
        Include the PlayCoinKrazy.com branding.`,
      },
    ],
  });

  const html = response.choices[0].message.content as string;

  return {
    subject: `🎉 Congratulations! You Won $${winAmount.toFixed(2)} at ${gameName}!`,
    html,
    text: `Congratulations! You won $${winAmount.toFixed(2)} playing ${gameName}. Your new balance is $${totalBalance.toFixed(2)}.`,
  };
}

export async function generateRedemptionConfirmationEmail(
  userName: string,
  amount: number,
  method: string,
  transactionId: string
): Promise<EmailTemplate> {
  const response = await invokeLLM({
    messages: [
      {
        role: "system",
        content: `You are an email template generator for CoinKrazy casino. Generate professional HTML emails.
        Always include the CoinKrazy branding and keep emails mobile-friendly.
        Return ONLY valid HTML (no markdown, no code blocks).`,
      },
      {
        role: "user",
        content: `Generate an HTML email confirming a redemption request.
        Player name: ${userName}
        Amount: $${amount.toFixed(2)}
        Method: ${method}
        Transaction ID: ${transactionId}
        Processing time: 1-3 business days
        
        Include status tracking information and support contact details.
        Include the PlayCoinKrazy.com branding.`,
      },
    ],
  });

  const html = response.choices[0].message.content as string;

  return {
    subject: `Redemption Confirmed - $${amount.toFixed(2)} via ${method}`,
    html,
    text: `Your redemption of $${amount.toFixed(2)} via ${method} has been confirmed. Transaction ID: ${transactionId}. Processing time: 1-3 business days.`,
  };
}

export async function generateLeaderboardAchievementEmail(
  userName: string,
  rank: number,
  totalWinnings: number
): Promise<EmailTemplate> {
  const response = await invokeLLM({
    messages: [
      {
        role: "system",
        content: `You are an email template generator for CoinKrazy casino. Generate professional HTML emails.
        Always include the CoinKrazy branding and keep emails mobile-friendly.
        Return ONLY valid HTML (no markdown, no code blocks).`,
      },
      {
        role: "user",
        content: `Generate an HTML email celebrating a player's leaderboard achievement.
        Player name: ${userName}
        Rank: #${rank}
        Total winnings: $${totalWinnings.toFixed(2)}
        
        Make it celebratory and include a link to view the leaderboard.
        Include the PlayCoinKrazy.com branding.`,
      },
    ],
  });

  const html = response.choices[0].message.content as string;

  return {
    subject: `🏆 You're Ranked #${rank} on the CoinKrazy Leaderboard!`,
    html,
    text: `Congratulations! You've reached rank #${rank} on the CoinKrazy leaderboard with $${totalWinnings.toFixed(2)} in total winnings.`,
  };
}

export async function generateKYCApprovedEmail(userName: string): Promise<EmailTemplate> {
  const response = await invokeLLM({
    messages: [
      {
        role: "system",
        content: `You are an email template generator for CoinKrazy casino. Generate professional HTML emails.
        Always include the CoinKrazy branding and keep emails mobile-friendly.
        Return ONLY valid HTML (no markdown, no code blocks).`,
      },
      {
        role: "user",
        content: `Generate an HTML email notifying a player that their KYC verification has been approved.
        Player name: ${userName}
        
        Include information about their new account status and any benefits they now have access to.
        Include the PlayCoinKrazy.com branding.`,
      },
    ],
  });

  const html = response.choices[0].message.content as string;

  return {
    subject: "✅ Your KYC Verification Has Been Approved!",
    html,
    text: `Your KYC verification has been approved! You now have full access to all CoinKrazy features.`,
  };
}

export async function generateWelcomeEmail(userName: string, signupBonus: number): Promise<EmailTemplate> {
  const response = await invokeLLM({
    messages: [
      {
        role: "system",
        content: `You are an email template generator for CoinKrazy casino. Generate professional HTML emails.
        Always include the CoinKrazy branding and keep emails mobile-friendly.
        Return ONLY valid HTML (no markdown, no code blocks).`,
      },
      {
        role: "user",
        content: `Generate a welcome email for a new player at CoinKrazy casino.
        Player name: ${userName}
        Signup bonus: $${signupBonus.toFixed(2)} in free coins
        
        Include information about available games, how to get started, and responsible gaming resources.
        Include the PlayCoinKrazy.com branding.`,
      },
    ],
  });

  const html = response.choices[0].message.content as string;

  return {
    subject: "🎉 Welcome to CoinKrazy - Your $" + signupBonus.toFixed(2) + " Bonus Awaits!",
    html,
    text: `Welcome to CoinKrazy! You've received $${signupBonus.toFixed(2)} in free coins to get started. Play 700+ casino games and compete for real prizes!`,
  };
}

export async function generateLargeWinEmail(
  userName: string,
  gameName: string,
  winAmount: number,
  multiplier: number
): Promise<EmailTemplate> {
  const response = await invokeLLM({
    messages: [
      {
        role: "system",
        content: `You are an email template generator for CoinKrazy casino. Generate professional HTML emails.
        Always include the CoinKrazy branding and keep emails mobile-friendly.
        Return ONLY valid HTML (no markdown, no code blocks).`,
      },
      {
        role: "user",
        content: `Generate an HTML email celebrating a LARGE win at the casino.
        Player name: ${userName}
        Game: ${gameName}
        Win amount: $${winAmount.toFixed(2)}
        Multiplier: ${multiplier}x
        
        Make this VERY celebratory with emojis and excitement. This is a big win!
        Include the PlayCoinKrazy.com branding and encourage sharing the win.`,
      },
    ],
  });

  const html = response.choices[0].message.content as string;

  return {
    subject: `🤑 HUGE WIN! You Won $${winAmount.toFixed(2)} at ${gameName}! 🤑`,
    html,
    text: `CONGRATULATIONS! You just won $${winAmount.toFixed(2)} with a ${multiplier}x multiplier on ${gameName}! Share your win with friends!`,
  };
}

/**
 * Mock email sending function
 * In production, this would integrate with SendGrid, AWS SES, or similar
 */
export async function sendEmail(
  to: string,
  template: EmailTemplate
): Promise<{ success: boolean; messageId?: string; error?: string }> {
  try {
    // In production, integrate with email service
    console.log(`📧 Email sent to ${to}`);
    console.log(`Subject: ${template.subject}`);

    return {
      success: true,
      messageId: `msg_${Date.now()}`,
    };
  } catch (error) {
    console.error("Email send failed:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "Unknown error",
    };
  }
}
