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

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '20')
    const status = searchParams.get('status')
    const role = searchParams.get('role')
    const areaId = searchParams.get('areaId')
    const search = searchParams.get('search')
    const connectionType = searchParams.get('connectionType')
    const resellerId = searchParams.get('resellerId')

    const where: Record<string, unknown> = {}

    if (status) where.status = status
    if (role) where.role = role
    if (areaId) where.areaId = areaId
    if (connectionType) where.connectionType = connectionType
    if (resellerId) where.resellerId = resellerId
    if (search) {
      where.OR = [
        { name: { contains: search } },
        { email: { contains: search } },
        { phone: { contains: search } },
        { username: { contains: search } },
      ]
    }

    const [users, total] = await Promise.all([
      db.user.findMany({
        where,
        include: {
          area: true,
          reseller: { select: { id: true, name: true, email: true } },
          _count: {
            select: {
              subscriptions: { where: { status: 'ACTIVE' } },
              invoices: true,
              tickets: { where: { status: { in: ['OPEN', 'IN_PROGRESS'] } } },
            },
          },
        },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * limit,
        take: limit,
      }),
      db.user.count({ where }),
    ])

    const usersWithoutPassword = users.map(({ password: _, ...user }) => user)

    return NextResponse.json({
      success: true,
      data: {
        users: usersWithoutPassword,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit),
        },
      },
    })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}
