import { getSession } from '@/lib/session'
import { checkSecurityToken } from '@/lib/security-token'
import { getAccountIdByCharacterName } from '@/lib/characters'
import { transferDPoints } from '@/lib/dpoints'

/**
 * Transfiere PD desde la cuenta en sesión a la cuenta dueña del personaje
 * indicado. Requiere el token de seguridad de la cuenta. Acción irreversible.
 */
export async function POST(request: Request) {
  const session = await getSession()
  if (!session.accountId || !session.username) {
    return Response.json({ success: false, error: 'notAuthenticated' }, { status: 401 })
  }

  let body: Record<string, unknown> = {}
  try {
    body = await request.json()
  } catch {
    return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })
  }

  const character = String(body.character ?? '').trim()
  const token = String(body.token ?? '').trim()
  const amount = Number(body.amount)

  if (!character || !token) return Response.json({ success: false, error: 'missingFields' })
  if (!Number.isInteger(amount) || amount <= 0) return Response.json({ success: false, error: 'invalidAmount' })

  if (!(await checkSecurityToken(session.accountId, token))) {
    return Response.json({ success: false, error: 'invalidToken' })
  }

  const destAccountId = await getAccountIdByCharacterName(character)
  if (!destAccountId) return Response.json({ success: false, error: 'characterNotFound' })
  if (destAccountId === session.accountId) return Response.json({ success: false, error: 'sameAccount' })

  const result = await transferDPoints(session.accountId, destAccountId, amount)
  return Response.json(result)
}
