import { getSession } from '@/lib/session'
import { isAdmin } from '@/lib/admin'
import { searchAccounts, banAccount, unbanAccount } from '@/lib/admin-users'

/** Búsqueda de cuentas: GET /api/admin/users?q=... */
export async function GET(request: Request) {
  const session = await getSession()
  if (!(await isAdmin(session))) return Response.json({ success: false, error: 'forbidden' }, { status: 403 })
  const q = (new URL(request.url).searchParams.get('q') || '').trim()
  if (q.length < 2) return Response.json({ success: true, accounts: [] })
  const accounts = await searchAccounts(q)
  return Response.json({ success: true, accounts })
}

/** Ban/unban: POST /api/admin/users { accountId, action, reason?, days? } */
export async function POST(request: Request) {
  const session = await getSession()
  if (!(await isAdmin(session))) return Response.json({ success: false, error: 'forbidden' }, { status: 403 })

  let b: Record<string, unknown> = {}
  try { b = await request.json() } catch { return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 }) }
  const accountId = Number(b.accountId)
  const action = String(b.action ?? '')
  if (!accountId) return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })

  if (action === 'ban') {
    const reason = String(b.reason ?? '').trim() || 'Baneado desde el panel de administración'
    const days = Number(b.days) || 0
    const bannedBy = session.username || session.bnetEmail || 'admin'
    const ok = await banAccount(accountId, reason, bannedBy, days)
    return Response.json({ success: ok })
  }
  if (action === 'unban') {
    const ok = await unbanAccount(accountId)
    return Response.json({ success: ok })
  }
  return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })
}
