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

/**
 * Pre-check whether an email exists before sending a magic link.
 * This is a closed platform (no self-registration) so revealing
 * email existence is acceptable and helps users who mistype.
 * Rate-limited to 10 requests per 15 minutes per IP.
 */
export async function POST(req: NextRequest) {
  try {
    const ip = req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ?? 'unknown'
    const rateResult = checkRateLimit(`check-email:${ip}`, 10, 15 * 60 * 1000)
    if (!rateResult.success) {
      return NextResponse.json(
        { exists: false, error: 'Too many requests' },
        { status: 429 },
      )
    }

    const { email } = await req.json()
    if (!email || typeof email !== 'string') {
      return NextResponse.json({ exists: false }, { status: 400 })
    }

    const user = await prisma.user.findFirst({
      where: { email: { equals: email.toLowerCase().trim(), mode: 'insensitive' } },
      select: { status: true },
    })

    const exists = !!user && user.status !== 'SUSPENDED'
    return NextResponse.json({ exists })
  } catch {
    return NextResponse.json({ exists: false }, { status: 500 })
  }
}
