import { NextRequest, NextResponse } from 'next/server'
import nodemailer from 'nodemailer'
import { checkRateLimit } from '@/lib/rate-limit'
import { auth } from '@/lib/auth'

const MAIL_DOMAIN = process.env.POSTE_MAIL_DOMAIN || 'monaco-opc.com'
const SMTP_HOST = process.env.SMTP_HOST || 'localhost'
const SMTP_PORT = parseInt(process.env.SMTP_PORT || '587')

export async function POST(request: NextRequest): Promise<NextResponse> {
  // Verify authenticated session
  const session = await auth()
  if (!session?.user?.email) {
    return NextResponse.json(
      { error: 'Authentication required.' },
      { status: 401 }
    )
  }

  const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || 'unknown'
  const rateLimit = checkRateLimit(`email-verify:${ip}`, 5, 15 * 60 * 1000)

  if (!rateLimit.success) {
    return NextResponse.json(
      { error: 'Too many attempts. Please try again later.' },
      { status: 429 }
    )
  }

  try {
    const body = await request.json()
    const { email, password } = body as { email: string; password: string }

    if (!email || !password) {
      return NextResponse.json(
        { error: 'Email and password are required.' },
        { status: 400 }
      )
    }

    const emailLower = email.toLowerCase().trim()

    // Verify the user can only check their own email credentials
    if (emailLower !== session.user.email.toLowerCase()) {
      return NextResponse.json(
        { error: 'You can only verify your own email credentials.' },
        { status: 403 }
      )
    }

    if (!emailLower.endsWith(`@${MAIL_DOMAIN}`)) {
      return NextResponse.json(
        { error: `Email must be an @${MAIL_DOMAIN} address.` },
        { status: 400 }
      )
    }

    const transporter = nodemailer.createTransport({
      host: SMTP_HOST,
      port: SMTP_PORT,
      secure: SMTP_PORT === 465,
      auth: {
        user: emailLower,
        pass: password,
      },
      connectionTimeout: 10000,
      greetingTimeout: 10000,
    })

    try {
      await transporter.verify()
      return NextResponse.json({ valid: true })
    } catch {
      return NextResponse.json({ valid: false, error: 'Invalid email or password.' })
    } finally {
      transporter.close()
    }
  } catch {
    return NextResponse.json(
      { error: 'Invalid request.' },
      { status: 400 }
    )
  }
}
