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

export async function POST(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getSession()
    if (!session || !isAdmin(session.role)) {
      return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 403 })
    }

    const target = await (prisma as any).user.findUnique({
      where: { id: params.id },
      include: { memberships: true },
    })
    if (!target) {
      return NextResponse.json({ error: 'Benutzer nicht gefunden' }, { status: 404 })
    }

    // TENANT_ADMIN: only reset users in same tenant
    if (session.role !== 'SERVER_ADMIN') {
      const inSameTenant = target.memberships?.some((m: any) => m.tenantId === session.tenantId)
      if (!inSameTenant) {
        return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
      }
    }

    // Generate reset token
    const resetToken = randomBytes(32).toString('hex')
    const resetTokenExpiry = new Date(Date.now() + 24 * 60 * 60 * 1000) // 24 hours for admin-initiated

    await (prisma as any).user.update({
      where: { id: params.id },
      data: { resetToken, resetTokenExpiry },
    })

    const host = req.headers.get('host') || 'localhost:3000'
    const protocol = host.includes('localhost') ? 'http' : 'https'
    const resetUrl = `${protocol}://${host}/reset-password?token=${resetToken}`

    // Try to send email
    const smtpConfig = await getSmtpConfig()
    let emailSent = false

    if (smtpConfig) {
      try {
        await sendEmail(
          target.email,
          'Passwort zurücksetzen – Lageplan',
          `
          <div style="font-family: sans-serif; max-width: 500px; margin: 0 auto;">
            <h2 style="color: #dc2626;">Passwort zurücksetzen</h2>
            <p>Hallo ${target.name},</p>
            <p>Ein Administrator hat eine Passwort-Zurücksetzung für Ihr Konto angefordert.</p>
            <p style="margin: 24px 0;">
              <a href="${resetUrl}" style="background: #dc2626; color: white; padding: 12px 24px; border-radius: 6px; text-decoration: none; font-weight: bold;">
                Neues Passwort setzen
              </a>
            </p>
            <p style="color: #666; font-size: 14px;">Dieser Link ist 24 Stunden gültig.</p>
            <hr style="border: none; border-top: 1px solid #eee; margin: 24px 0;" />
            <p style="color: #999; font-size: 12px;">Lageplan – Feuerwehr Krokier-App</p>
          </div>
          `
        )
        emailSent = true
      } catch (emailErr) {
        console.error('Failed to send reset email:', emailErr)
      }
    }

    return NextResponse.json({
      success: true,
      emailSent,
      resetUrl: emailSent ? undefined : resetUrl,
      message: emailSent
        ? `Reset-Link wurde an ${target.email} gesendet.`
        : 'SMTP nicht konfiguriert. Reset-Link wurde generiert.',
    })
  } catch (error) {
    console.error('Admin reset password error:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}
