import { NextResponse } from 'next/server'
import bcrypt from 'bcryptjs'
import { prisma } from '@/lib/prisma'
import { sanitizeString, MAX_LENGTHS } from '@/lib/validate'

export async function POST(request: Request) {
  try {
    const body = await request.json()
    const name = sanitizeString(body.name, MAX_LENGTHS.name)
    const email = sanitizeString(body.email, MAX_LENGTHS.email)
    const password = typeof body.password === 'string' ? body.password.slice(0, MAX_LENGTHS.password) : ''
    const oabNumber = body.oabNumber ? sanitizeString(body.oabNumber, MAX_LENGTHS.oabNumber) : null
    const oabState = body.oabState ? sanitizeString(body.oabState, MAX_LENGTHS.oabState) : null
    const phone = body.phone ? sanitizeString(body.phone, MAX_LENGTHS.phone) : null

    // Validate required fields
    if (!name || !email || !password) {
      return NextResponse.json(
        { error: 'Nome, email e senha são obrigatórios' },
        { status: 400 }
      )
    }

    // Validate email format
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      return NextResponse.json(
        { error: 'Email inválido' },
        { status: 400 }
      )
    }

    // Validate password length
    if (password.length < 8) {
      return NextResponse.json(
        { error: 'Senha deve ter pelo menos 8 caracteres' },
        { status: 400 }
      )
    }

    // Validate OAB number format if provided
    if (oabNumber) {
      const cleanOab = oabNumber.replace(/\D/g, '')
      if (!/^\d{3,7}$/.test(cleanOab)) {
        return NextResponse.json(
          { error: 'Número OAB inválido (3-7 dígitos)' },
          { status: 400 }
        )
      }
    }

    // Check email uniqueness
    const existingUser = await prisma.user.findUnique({
      where: { email: email.toLowerCase() },
    })

    if (existingUser) {
      return NextResponse.json(
        { error: 'Este email já está cadastrado' },
        { status: 409 }
      )
    }

    // Hash password
    const hashedPassword = await bcrypt.hash(password, 12)

    // Create user with FREE plan and 5 credits
    const user = await prisma.user.create({
      data: {
        name,
        email: email.toLowerCase(),
        password: hashedPassword,
        role: 'FREE',
        plan: 'FREE',
        credits: 5,
        oabNumber,
        oabState,
        phone,
      },
      select: {
        id: true,
        name: true,
        email: true,
        plan: true,
        credits: true,
      },
    })

    return NextResponse.json(
      { message: 'Conta criada com sucesso', user },
      { status: 201 }
    )
  } catch (error) {
    console.error('Register error:', error)
    return NextResponse.json(
      { error: 'Erro interno do servidor' },
      { status: 500 }
    )
  }
}
