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(['ADMIN'])(request)
    if ('error' in authResult) return authResult.error

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

    const where: Prisma.UserWhereInput = {}

    if (role) {
      where.role = role as Prisma.EnumUserRoleFilter['equals']
    }

    if (isActive !== null && isActive !== undefined && isActive !== '') {
      where.isActive = isActive === 'true'
    }

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

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

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

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

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

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

    const validRoles = ['CUSTOMER', 'SUPERVISOR', 'MANAGER', 'ADMIN']
    if (!role || !validRoles.includes(role)) {
      return NextResponse.json(
        { error: 'Rol inválido. Debe ser: CUSTOMER, SUPERVISOR, MANAGER o ADMIN' },
        { 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 createData: Prisma.UserCreateInput = {
      email: email.toLowerCase().trim(),
      name: name.trim(),
      company: company?.trim() || null,
      phone: phone?.trim() || null,
      passwordHash,
      role: role as Prisma.EnumUserRoleFilter['equals'],
    }

    // If creating a customer, assign the admin as the creator (assignedBy)
    if (role === 'CUSTOMER') {
      createData.assignedBy = {
        connect: { id: adminUser.id },
      }
    }

    const newUser = await db.user.create({
      data: createData,
      select: {
        id: true,
        email: true,
        name: true,
        company: true,
        phone: true,
        role: true,
        isActive: true,
        createdAt: true,
        assignedBy: { select: { id: true, name: true } },
      },
    })

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

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