import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import prisma from '@/lib/prisma'
import { authOptions } from '@/lib/auth'

export async function GET(req: NextRequest) {
  const session = await getServerSession(authOptions)
  if (session?.user?.role !== 'ADMIN') return NextResponse.json({ error: 'Forbidden' }, { status: 403 })

  const { searchParams } = new URL(req.url)
  const page = parseInt(searchParams.get('page') || '1')
  const limit = parseInt(searchParams.get('limit') || '20')
  const search = searchParams.get('search') || ''
  const skip = (page - 1) * limit

  const [users, total] = await Promise.all([
    prisma.user.findMany({
      where: search
        ? {
            OR: [
              { name: { contains: search } },
              { email: { contains: search } },
            ],
          }
        : {},
      select: {
        id: true,
        name: true,
        email: true,
        role: true,
        balance: true,
        isBanned: true,
        createdAt: true,
        _count: { select: { orders: true } },
      },
      orderBy: { createdAt: 'desc' },
      skip,
      take: limit,
    }),
    prisma.user.count({
      where: search ? { OR: [{ name: { contains: search } }, { email: { contains: search } }] } : {},
    }),
  ])

  return NextResponse.json({ users, total, page, limit, pages: Math.ceil(total / limit) })
}

export async function PATCH(req: NextRequest) {
  const session = await getServerSession(authOptions)
  if (session?.user?.role !== 'ADMIN') return NextResponse.json({ error: 'Forbidden' }, { status: 403 })

  const { searchParams } = new URL(req.url)
  const userId = searchParams.get('id')
  if (!userId) return NextResponse.json({ error: 'User ID diperlukan' }, { status: 400 })

  const body = await req.json()
  const updateData: any = {}

  if (body.isBanned !== undefined) updateData.isBanned = body.isBanned
  if (body.banReason !== undefined) updateData.banReason = body.banReason
  if (body.role !== undefined) updateData.role = body.role
  if (body.balance !== undefined) {
    // Edit balance - also create a wallet transaction log
    const user = await prisma.user.findUnique({ where: { id: userId } })
    if (user) {
      const diff = body.balance - Number(user.balance)
      await prisma.walletTransaction.create({
        data: {
          userId,
          type: diff > 0 ? 'BONUS' : 'PAYMENT',
          amount: Math.abs(diff),
          balanceBefore: user.balance,
          balanceAfter: body.balance,
          description: `Admin adjustment: ${body.reason || 'Manual balance update'}`,
          status: 'SUCCESS',
        },
      })
    }
    updateData.balance = body.balance
  }

  const updated = await prisma.user.update({
    where: { id: userId },
    data: updateData,
    select: { id: true, name: true, email: true, role: true, balance: true, isBanned: true },
  })

  return NextResponse.json({ user: updated })
}
