<?php

namespace App\Http\Controllers\Admin;

use App\FiveM\Contracts\FrameworkAdapter;
use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class PlayerManagerController extends Controller
{
    public function index(Request $request, FrameworkAdapter $adapter): Response
    {
        $characters = $adapter->paginateCharacters(25, $request->string('search')->value() ?: null);

        return Inertia::render('Admin/Players/Index', [
            'characters' => $characters->through(fn ($c) => $c->toArray()),
            'search' => $request->string('search')->value(),
        ]);
    }

    public function show(FrameworkAdapter $adapter, string $citizenId): Response
    {
        $character = $adapter->findByCitizenId($citizenId);

        abort_if(! $character, 404);

        return Inertia::render('Admin/Players/Show', [
            'character' => $character->toArray(),
            'vehicles' => $adapter->vehiclesForCitizen($citizenId),
            'houses' => $adapter->housesForCitizen($citizenId),
        ]);
    }

    /**
     * Admin-initiated money adjustment for a specific player, distinct from
     * the bulk EconomyController (this is the per-player "edit" action on
     * the Player Manager detail page).
     */
    public function update(Request $request, FrameworkAdapter $adapter, string $citizenId): RedirectResponse
    {
        $data = $request->validate([
            'account' => ['required', 'in:cash,bank,crypto'],
            'delta' => ['required', 'integer'],
        ]);

        $adapter->adjustMoney($citizenId, $data['account'], $data['delta']);

        AuditLog::record('player.money_adjusted', null, [...$data, 'citizen_id' => $citizenId]);

        return back()->with('success', 'Player balance updated.');
    }
}
