<?php

namespace App\Http\Controllers\Player;

use App\FiveM\Contracts\FrameworkAdapter;
use App\FiveM\DTOs\CharacterData;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class CharacterController extends Controller
{
    public function index(Request $request, FrameworkAdapter $adapter): Response
    {
        $user = $request->user();

        $characters = $user->fivem_license
            ? $adapter->findAllByLicense($user->fivem_license)
            : collect();

        return Inertia::render('Player/Characters/Index', [
            'characters' => $characters->map->toArray(),
        ]);
    }

    public function show(Request $request, FrameworkAdapter $adapter, string $citizenId): Response
    {
        $character = $this->ownedCharacterOrAbort($request, $adapter, $citizenId);

        return Inertia::render('Player/Characters/Show', [
            'character' => $character->toArray(),
        ]);
    }

    /**
     * Every player-facing controller that accepts a {citizenId} route
     * parameter (Inventory, Vehicle, House, Bank, Job, Gang, Stats)
     * resolves the character through this helper so ownership is checked
     * in one place — a player can never view another player's character
     * data by guessing/incrementing a citizen ID in the URL.
     */
    public static function ownedCharacterOrAbort(Request $request, FrameworkAdapter $adapter, string $citizenId): CharacterData
    {
        $user = $request->user();
        $character = $adapter->findByCitizenId($citizenId);

        abort_if(! $character, 404);
        abort_unless($user->fivem_license && $character->license === $user->fivem_license, 403);

        return $character;
    }
}
