import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getSession, isServerAdmin } from '@/lib/auth'
import { sendEmail, getSmtpConfig } from '@/lib/email'

// POST: Check all tenants in TRIAL status and send reminder emails
// Can be called manually by SERVER_ADMIN or via cron
export async function POST(req: NextRequest) {
  try {
    // Auth: only SERVER_ADMIN or internal cron (via secret header)
    const cronSecret = req.headers.get('x-cron-secret')
    const expectedSecret = process.env.CRON_SECRET
    const isCron = expectedSecret && cronSecret === expectedSecret

    if (!isCron) {
      const user = await getSession()
      if (!user || !isServerAdmin(user.role)) {
        return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 403 })
      }
    }

    const smtpConfig = await getSmtpConfig()
    if (!smtpConfig) {
      return NextResponse.json({ error: 'SMTP nicht konfiguriert', sent: 0 }, { status: 200 })
    }

    const now = new Date()

    // Find all tenants in TRIAL status with trialEndsAt set
    const trialTenants = await (prisma as any).tenant.findMany({
      where: {
        subscriptionStatus: 'TRIAL',
        trialEndsAt: { not: null },
        isActive: true,
      },
      include: {
        memberships: {
          where: { role: 'TENANT_ADMIN' },
          include: { user: { select: { email: true, name: true } } },
        },
      },
    })

    const results: { tenant: string; daysLeft: number; emailsSent: number; action: string }[] = []

    for (const tenant of trialTenants) {
      const trialEnd = new Date(tenant.trialEndsAt)
      const diffMs = trialEnd.getTime() - now.getTime()
      const daysLeft = Math.ceil(diffMs / (1000 * 60 * 60 * 24))

      // Determine which reminder to send (only specific days to avoid spam)
      // Send at: 14 days, 7 days, 3 days, 1 day before, and on expiry day
      const reminderDays = [14, 7, 3, 1, 0]
      if (!reminderDays.includes(daysLeft)) {
        results.push({ tenant: tenant.name, daysLeft, emailsSent: 0, action: 'skipped' })
        continue
      }

      // Check if we already sent a reminder for this day (using SystemSetting as log)
      const reminderKey = `trial_reminder_${tenant.id}_${daysLeft}`
      const existing = await (prisma as any).systemSetting.findUnique({
        where: { key: reminderKey },
      })
      if (existing) {
        results.push({ tenant: tenant.name, daysLeft, emailsSent: 0, action: 'already_sent' })
        continue
      }

      // Get admin emails for this tenant
      const adminEmails = tenant.memberships
        .filter((m: any) => m.user?.email)
        .map((m: any) => ({ email: m.user.email, name: m.user.name }))

      if (adminEmails.length === 0) {
        results.push({ tenant: tenant.name, daysLeft, emailsSent: 0, action: 'no_admins' })
        continue
      }

      // Build email content based on days left
      let subject: string
      let heading: string
      let bodyText: string
      let urgencyColor: string

      if (daysLeft <= 0) {
        subject = `Ihre Testphase bei Lageplan ist abgelaufen`
        heading = 'Testphase abgelaufen'
        bodyText = `Ihre 45-tägige Testphase für <strong>${tenant.name}</strong> ist heute abgelaufen. Ihr Konto wurde automatisch auf den <strong>Free-Plan</strong> umgestellt. Einige Funktionen sind nun eingeschränkt.`
        urgencyColor = '#dc2626'
      } else if (daysLeft === 1) {
        subject = `Lageplan: Ihre Testphase endet morgen`
        heading = 'Noch 1 Tag'
        bodyText = `Ihre Testphase für <strong>${tenant.name}</strong> endet <strong>morgen</strong>. Danach wechselt Ihr Konto automatisch zum Free-Plan.`
        urgencyColor = '#ea580c'
      } else if (daysLeft <= 3) {
        subject = `Lageplan: Noch ${daysLeft} Tage in Ihrer Testphase`
        heading = `Noch ${daysLeft} Tage`
        bodyText = `Ihre Testphase für <strong>${tenant.name}</strong> endet in <strong>${daysLeft} Tagen</strong>. Upgraden Sie rechtzeitig, um alle Funktionen zu behalten.`
        urgencyColor = '#ea580c'
      } else if (daysLeft <= 7) {
        subject = `Lageplan: Noch ${daysLeft} Tage in Ihrer Testphase`
        heading = `Noch ${daysLeft} Tage`
        bodyText = `Ihre Testphase für <strong>${tenant.name}</strong> endet in ${daysLeft} Tagen. Nutzen Sie die verbleibende Zeit, um alle Funktionen auszuprobieren.`
        urgencyColor = '#ca8a04'
      } else {
        subject = `Lageplan: Noch ${daysLeft} Tage in Ihrer Testphase`
        heading = `Noch ${daysLeft} Tage`
        bodyText = `Ihre Testphase für <strong>${tenant.name}</strong> läuft noch ${daysLeft} Tage. Viel Spass beim Testen!`
        urgencyColor = '#2563eb'
      }

      const trialEndStr = trialEnd.toLocaleDateString('de-CH', {
        day: '2-digit', month: '2-digit', year: 'numeric',
      })

      const html = `
        <div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 520px; margin: 0 auto;">
          <div style="background: ${urgencyColor}; color: white; padding: 16px 24px; border-radius: 8px 8px 0 0;">
            <h2 style="margin: 0; font-size: 18px;">${heading}</h2>
          </div>
          <div style="border: 1px solid #e5e7eb; border-top: none; padding: 24px; border-radius: 0 0 8px 8px;">
            <p style="margin: 0 0 16px; line-height: 1.6; color: #374151;">${bodyText}</p>
            <table style="width: 100%; border-collapse: collapse; margin: 16px 0;">
              <tr>
                <td style="padding: 8px 0; color: #6b7280; font-size: 14px;">Organisation</td>
                <td style="padding: 8px 0; font-weight: 600; text-align: right;">${tenant.name}</td>
              </tr>
              <tr>
                <td style="padding: 8px 0; color: #6b7280; font-size: 14px;">Ablaufdatum</td>
                <td style="padding: 8px 0; font-weight: 600; text-align: right;">${trialEndStr}</td>
              </tr>
              <tr>
                <td style="padding: 8px 0; color: #6b7280; font-size: 14px;">Aktueller Plan</td>
                <td style="padding: 8px 0; font-weight: 600; text-align: right;">Testversion (Trial)</td>
              </tr>
            </table>
            ${daysLeft > 0 ? `
              <p style="margin: 16px 0 0; font-size: 13px; color: #6b7280;">
                Sie müssen nichts tun — nach Ablauf der Testphase wechselt Ihr Konto automatisch zum kostenlosen Free-Plan.
                Für erweiterte Funktionen können Sie jederzeit upgraden.
              </p>
            ` : `
              <p style="margin: 16px 0 0; font-size: 13px; color: #6b7280;">
                Ihre Daten bleiben erhalten. Sie können jederzeit auf einen kostenpflichtigen Plan upgraden, um alle Funktionen wieder freizuschalten.
              </p>
            `}
            <hr style="border: none; border-top: 1px solid #e5e7eb; margin: 20px 0;" />
            <p style="margin: 0; font-size: 12px; color: #9ca3af;">
              Lageplan — Digitale Lagepläne für die Feuerwehr<br/>
              Diese E-Mail wurde automatisch gesendet.
            </p>
          </div>
        </div>
      `

      let emailsSent = 0
      for (const admin of adminEmails) {
        try {
          await sendEmail(admin.email, subject, html)
          emailsSent++
        } catch (e) {
          console.error(`Failed to send trial reminder to ${admin.email}:`, e)
        }
      }

      // Log that we sent this reminder (prevent duplicates)
      await (prisma as any).systemSetting.create({
        data: {
          key: reminderKey,
          value: JSON.stringify({
            sentAt: now.toISOString(),
            daysLeft,
            emailsSent,
            recipients: adminEmails.map((a: any) => a.email),
          }),
          isSecret: false,
          category: 'trial_reminders',
        },
      })

      results.push({ tenant: tenant.name, daysLeft, emailsSent, action: 'sent' })

      // If trial has expired, downgrade to FREE
      if (daysLeft <= 0) {
        await (prisma as any).tenant.update({
          where: { id: tenant.id },
          data: {
            subscriptionStatus: 'EXPIRED',
            plan: 'FREE',
          },
        })
        results.push({ tenant: tenant.name, daysLeft, emailsSent: 0, action: 'downgraded_to_free' })
      }
    }

    return NextResponse.json({
      success: true,
      processed: trialTenants.length,
      results,
    })
  } catch (error) {
    console.error('Trial reminder error:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}
