import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'

function getBaseUrl(req: NextRequest): string {
  // Use NEXTAUTH_URL if set, ensure it has a protocol
  if (process.env.NEXTAUTH_URL) {
    const url = process.env.NEXTAUTH_URL.trim()
    if (url.startsWith('http://') || url.startsWith('https://')) return url
    return `https://${url}`
  }
  const proto = req.headers.get('x-forwarded-proto') || 'https'
  const host = req.headers.get('host') || 'localhost:3000'
  return `${proto}://${host}`
}

export async function GET(req: NextRequest) {
  const base = getBaseUrl(req)
  try {
    const token = req.nextUrl.searchParams.get('token')

    if (!token) {
      return NextResponse.redirect(`${base}/login?error=invalid-token`)
    }

    // Find user by verification token
    const user = await (prisma as any).user.findFirst({
      where: { emailVerificationToken: token },
    })

    if (!user) {
      return NextResponse.redirect(`${base}/login?error=invalid-token`)
    }

    // Mark email as verified
    await (prisma as any).user.update({
      where: { id: user.id },
      data: {
        emailVerified: true,
        emailVerificationToken: null,
      },
    })

    // Redirect to login with success message
    return NextResponse.redirect(`${base}/login?verified=true`)
  } catch (error) {
    console.error('Email verification error:', error)
    return NextResponse.redirect(`${base}/login?error=verification-failed`)
  }
}
