// Email Integration Library
// Handles sending emails and AI-processed support emails

import nodemailer from 'nodemailer'
import { db } from '@/lib/db'

interface EmailConfig {
  host: string
  port: number
  secure: boolean
  user: string
  pass: string
  fromAddress: string
  fromName: string
}

/**
 * Get email configuration from environment variables
 */
function getConfig(): EmailConfig {
  return {
    host: process.env.EMAIL_HOST || 'smtp.gmail.com',
    port: parseInt(process.env.EMAIL_PORT || '587'),
    secure: process.env.EMAIL_SECURE === 'true',
    user: process.env.EMAIL_USER || '',
    pass: process.env.EMAIL_PASS || '',
    fromAddress: process.env.EMAIL_FROM || process.env.EMAIL_USER || '',
    fromName: process.env.EMAIL_FROM_NAME || 'Studo Guide',
  }
}

/**
 * Check if email is configured
 */
export function isConfigured(): boolean {
  const config = getConfig()
  return !!(config.user && config.pass)
}

/**
 * Create a nodemailer transporter
 */
function createTransporter() {
  const config = getConfig()
  return nodemailer.createTransport({
    host: config.host,
    port: config.port,
    secure: config.secure,
    auth: {
      user: config.user,
      pass: config.pass,
    },
  })
}

/**
 * Send an email
 */
export async function sendEmail(
  to: string,
  subject: string,
  body: string,
  options?: {
    html?: string
    attachments?: Array<{
      filename: string
      content: string | Buffer
      contentType?: string
    }>
  }
): Promise<boolean> {
  const config = getConfig()

  if (!isConfigured()) {
    console.warn('Email not configured. Would send:', { to, subject })
    await logEmail(to, subject, body, 'logged')
    return false
  }

  try {
    const transporter = createTransporter()

    const mailOptions: nodemailer.SendMailOptions = {
      from: `"${config.fromName}" <${config.fromAddress}>`,
      to,
      subject,
      text: body,
      html: options?.html || bodyToHtml(body),
      attachments: options?.attachments,
    }

    const info = await transporter.sendMail(mailOptions)
    await logEmail(to, subject, body, 'sent', info.messageId)
    return true
  } catch (error) {
    console.error('Failed to send email:', error instanceof Error ? error.message : error)
    await logEmail(to, subject, body, 'failed')
    return false
  }
}

/**
 * Process a support email with AI
 * Analyzes the email and generates a helpful response
 */
export async function processSupportEmail(
  _from: string,
  subject: string,
  body: string
): Promise<{ category: string; priority: string; suggestedResponse: string }> {
  try {
    // Import AI client dynamically to avoid circular dependencies
    const { chatCompletion } = await import('./ollama')

    const systemPrompt = `You are an AI assistant for Studo Guide, a South African education platform.
Analyze this support email and categorize it. Provide a helpful suggested response.

Categories: bursary_help, career_advice, technical_issue, account_problem, feedback, general
Priority: low, medium, high, urgent

Respond in JSON format:
{
  "category": "...",
  "priority": "...",
  "suggestedResponse": "..."
}

The suggested response should be helpful, professional, and in South African English context.`

    const response = await chatCompletion(
      [
        { role: 'system', content: systemPrompt },
        { role: 'user', content: `Subject: ${subject}\n\n${body}` },
      ],
      undefined,
      { temperature: 0.3 }
    )

    try {
      // Try to parse as JSON - extract it if wrapped in markdown code blocks
      let jsonStr = response.trim()
      const jsonMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/)
      if (jsonMatch) {
        jsonStr = jsonMatch[1].trim()
      }
      return JSON.parse(jsonStr)
    } catch {
      return {
        category: 'general',
        priority: 'medium',
        suggestedResponse: response,
      }
    }
  } catch (error) {
    console.error('Failed to process support email:', error)
    return {
      category: 'general',
      priority: 'medium',
      suggestedResponse:
        'Thank you for contacting Studo Guide. We have received your message and will respond shortly.',
    }
  }
}

/**
 * Send bursary alert notification to a user
 */
export async function sendBursaryAlert(
  userEmail: string,
  bursaries: Array<{
    title: string
    provider?: string
    closingDate?: string
    value?: string
    sourceUrl?: string
  }>
): Promise<boolean> {
  const subject = `🎓 New Bursary Opportunities - Studo Guide`

  let body = `Hello!\n\nWe found ${bursaries.length} new bursary opportunity that matches your profile:\n\n`

  bursaries.forEach((b, i) => {
    body += `${i + 1}. ${b.title}\n`
    if (b.provider) body += `   Provider: ${b.provider}\n`
    if (b.value) body += `   Value: ${b.value}\n`
    if (b.closingDate) body += `   Closing: ${b.closingDate}\n`
    if (b.sourceUrl) body += `   Apply: ${b.sourceUrl}\n`
    body += '\n'
  })

  body += `Log in to Studo Guide to view more details and apply.\n\nGood luck! 🍀\n- The Studo Guide Team`

  const html = bodyToHtml(body, 'New Bursary Opportunities')

  return sendEmail(userEmail, subject, body, { html })
}

/**
 * Send weekly progress digest to a user
 */
export async function sendWeeklyDigest(userId: string): Promise<boolean> {
  try {
    const user = await db.user.findUnique({
      where: { id: userId },
      include: {
        pointsLogs: {
          where: {
            createdAt: {
              gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
            },
          },
          orderBy: { createdAt: 'desc' },
          take: 10,
        },
      },
    })

    if (!user) return false

    const totalPointsThisWeek = user.pointsLogs.reduce((sum, log) => sum + log.points, 0)
    const unreadNotifications = await db.notification.count({
      where: { userId, isRead: false },
    })

    const firstName = user.firstName || 'Student'
    const subject = `📊 Your Weekly Studo Guide Progress`

    let body = `Hi ${firstName}!\n\nHere's your weekly progress update:\n\n`
    body += `📈 Points earned this week: ${totalPointsThisWeek}\n`
    body += `🏆 Total points: ${user.points}\n`
    body += `🔔 Unread notifications: ${unreadNotifications}\n`

    if (user.pointsLogs.length > 0) {
      body += `\nRecent activity:\n`
      user.pointsLogs.forEach((log) => {
        body += `  • ${log.description || log.action || 'Activity'} (${log.points > 0 ? '+' : ''}${log.points} points)\n`
      })
    }

    body += `\nKeep up the great work! 💪\n\n- The Studo Guide Team`

    const html = bodyToHtml(body, 'Your Weekly Progress')

    return sendEmail(user.email, subject, body, { html })
  } catch (error) {
    console.error('Failed to send weekly digest:', error)
    return false
  }
}

/**
 * Send welcome email to a new user
 */
export async function sendWelcomeEmail(userEmail: string, name: string): Promise<boolean> {
  const firstName = name.split(' ')[0] || 'Student'
  const subject = `🎉 Welcome to Studo Guide, ${firstName}!`

  const body = `Hi ${firstName}!

Welcome to Studo Guide - your AI-powered career and education companion!

Here's what you can do on our platform:

📚 Career Assessment
Take our AI-powered assessment to discover careers that match your interests and strengths.

🎓 Bursary Finder
Find bursaries and scholarships that match your profile and needs.

🏫 University Guide
Explore South African universities, courses, and admission requirements.

🤖 AI Career Chat
Chat with our AI assistant for personalized career and study advice.

📊 Track Your Progress
Earn points, track your academic results, and watch your journey grow!

Getting started is easy - just complete your profile and take the career assessment.

Good luck on your journey to an amazing future! 🌟

- The Studo Guide Team`

  const html = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 0; padding: 20px; background: #f5f6fa; }
    .container { max-width: 600px; margin: 0 auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
    .header { background: linear-gradient(135deg, #91C4D9 0%, #5b9ebd 100%); padding: 30px; text-align: center; color: white; }
    .header h1 { margin: 0; font-size: 24px; }
    .content { padding: 30px; color: #2c3e50; line-height: 1.6; }
    .feature { padding: 10px 0; border-bottom: 1px solid #eee; }
    .feature:last-child { border-bottom: none; }
    .feature-icon { font-size: 20px; margin-right: 10px; }
    .cta { display: inline-block; background: linear-gradient(135deg, #91C4D9 0%, #5b9ebd 100%); color: white; text-decoration: none; padding: 12px 30px; border-radius: 8px; margin: 20px 0; font-weight: bold; }
    .footer { text-align: center; padding: 20px; color: #7f8c8d; font-size: 12px; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>🎓 Welcome to Studo Guide!</h1>
      <p>Your Future Career Guide</p>
    </div>
    <div class="content">
      <p>Hi <strong>${firstName}</strong>!</p>
      <p>Welcome to Studo Guide - your AI-powered career and education companion!</p>
      
      <div class="feature"><span class="feature-icon">📚</span> <strong>Career Assessment</strong> - Discover careers matching your interests</div>
      <div class="feature"><span class="feature-icon">🎓</span> <strong>Bursary Finder</strong> - Find bursaries that match your profile</div>
      <div class="feature"><span class="feature-icon">🏫</span> <strong>University Guide</strong> - Explore SA universities and courses</div>
      <div class="feature"><span class="feature-icon">🤖</span> <strong>AI Career Chat</strong> - Get personalized career advice</div>
      <div class="feature"><span class="feature-icon">📊</span> <strong>Track Progress</strong> - Earn points and track your journey</div>
      
      <p style="text-align: center;"><a class="cta" href="https://studoguide.co.za">Get Started →</a></p>
      <p>Good luck on your journey to an amazing future! 🌟</p>
      <p>— The Studo Guide Team</p>
    </div>
    <div class="footer">
      <p>© ${new Date().getFullYear()} Studo Guide. All rights reserved.</p>
      <p>Empowering South African students to reach their full potential.</p>
    </div>
  </div>
</body>
</html>`

  return sendEmail(userEmail, subject, body, { html })
}

/**
 * Convert plain text to simple HTML
 */
function bodyToHtml(body: string, title?: string): string {
  const paragraphs = body
    .split('\n\n')
    .map((p) => p.trim())
    .filter(Boolean)
    .map((p) => {
      // Convert lines to HTML paragraphs or list items
      if (p.includes('\n') && p.includes('•')) {
        const lines = p
          .split('\n')
          .map((line) => line.trim().replace(/^•\s*/, ''))
          .filter(Boolean)
          .map((line) => `<li>${line}</li>`)
          .join('')
        return `<ul>${lines}</ul>`
      }
      return `<p>${p.replace(/\n/g, '<br>')}</p>`
    })
    .join('\n')

  return `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 0; padding: 20px; background: #f5f6fa; }
    .container { max-width: 600px; margin: 0 auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
    .header { background: linear-gradient(135deg, #91C4D9 0%, #5b9ebd 100%); padding: 20px 30px; color: white; }
    .header h2 { margin: 0; font-size: 20px; }
    .content { padding: 30px; color: #2c3e50; line-height: 1.6; }
    .footer { text-align: center; padding: 20px; color: #7f8c8d; font-size: 12px; }
    a { color: #5b9ebd; }
    ul { padding-left: 20px; }
    li { margin-bottom: 4px; }
  </style>
</head>
<body>
  <div class="container">
    ${title ? `<div class="header"><h2>${title}</h2></div>` : ''}
    <div class="content">${paragraphs}</div>
    <div class="footer">
      <p>© ${new Date().getFullYear()} Studo Guide. Your Future Career Guide.</p>
    </div>
  </div>
</body>
</html>`
}

/**
 * Log an email to the database
 */
async function logEmail(
  to: string,
  subject: string,
  body: string,
  status: string,
  externalId?: string
) {
  try {
    await db.emailLog.create({
      data: {
        to,
        subject,
        body: body.slice(0, 5000), // Truncate very long emails
        status,
        externalId,
      },
    })
  } catch (error) {
    console.error('Failed to log email:', error)
  }
}
