import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { requireAuth } from '@/lib/api-auth'
import { hashPassword } from '@/lib/auth'
import { sendUserCreatedEmail } from '@/lib/email'
import { Prisma } from '@prisma/client'

export async function GET(request: NextRequest) {
  try {
    const authResult = await requireAuth(['SUPERVISOR', 'MANAGER', 'ADMIN'])(request)
    if ('error' in authResult) return authResult.error

    const { searchParams } = new URL(request.url)
    const search = searchParams.get('search')
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '50')

    const where: Prisma.UserWhereInput = { role: 'CUSTOMER' }

    if (search) {
      where.OR = [
        { name: { contains: search } },
        { email: { contains: search } },
        { phone: { contains: search } },
        { company: { contains: search } },
      ]
    }

    const [customers, total] = await Promise.all([
      db.user.findMany({
        where,
        select: {
          id: true,
          email: true,
          name: true,
          company: true,
          phone: true,
          isActive: true,
          createdAt: true,
          assignedBy: { select: { id: true, name: true } },
          _count: { select: { reviews: true } },
        },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * limit,
        take: limit,
      }),
      db.user.count({ where }),
    ])

    return NextResponse.json({
      customers,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    })
  } catch (error) {
    console.error('Error al listar clientes:', error)
    return NextResponse.json(
      { error: 'Error interno del servidor' },
      { status: 500 }
    )
  }
}

export async function POST(request: NextRequest) {
  try {
    const authResult = await requireAuth(['SUPERVISOR', 'MANAGER', 'ADMIN'])(request)
    if ('error' in authResult) return authResult.error

    const { user } = authResult
    const body = await request.json()
    const { email, name, phone, password, company } = body

    if (!email || !name || !password) {
      return NextResponse.json(
        { error: 'Email, nombre y contraseña son requeridos' },
        { status: 400 }
      )
    }

    if (password.length < 6) {
      return NextResponse.json(
        { error: 'La contraseña debe tener al menos 6 caracteres' },
        { status: 400 }
      )
    }

    const existingUser = await db.user.findUnique({
      where: { email: email.toLowerCase().trim() },
    })

    if (existingUser) {
      return NextResponse.json(
        { error: 'Ya existe una cuenta con este email' },
        { status: 409 }
      )
    }

    const passwordHash = await hashPassword(password)

    const customer = await db.user.create({
      data: {
        email: email.toLowerCase().trim(),
        name: name.trim(),
        company: company?.trim() || null,
        phone: phone?.trim() || null,
        passwordHash,
        role: 'CUSTOMER',
        assignedById: user.role === 'SUPERVISOR' ? user.id : (body.assignedById || null),
      },
      select: {
        id: true,
        email: true,
        name: true,
        company: true,
        phone: true,
        isActive: true,
        createdAt: true,
        assignedBy: { select: { id: true, name: true } },
      },
    })

    // Send welcome email (non-blocking, don't fail if email fails)
    sendUserCreatedEmail({
      to: customer.email,
      name: customer.name,
      password,
      role: 'CUSTOMER',
    }).catch((err) => {
      console.error('Failed to send welcome email:', err)
    })

    return NextResponse.json({ customer }, { status: 201 })
  } catch (error) {
    console.error('Error al crear cliente:', error)
    return NextResponse.json(
      { error: 'Error interno del servidor' },
      { status: 500 }
    )
  }
}
