<?php

namespace App\Http\Controllers\Player;

use App\FiveM\Contracts\FrameworkAdapter;
use App\Http\Controllers\Controller;
use App\Models\Achievement;
use App\Models\CharacterAchievement;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

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

        $citizenIds = $user->fivem_license
            ? $adapter->findAllByLicense($user->fivem_license)->pluck('citizenId')
            : collect();

        $unlockedKeys = CharacterAchievement::query()
            ->whereIn('citizen_id', $citizenIds)
            ->with('achievement:id,key')
            ->get()
            ->pluck('achievement.key');

        return Inertia::render('Player/Achievements', [
            'achievements' => Achievement::query()->orderBy('name')->get()->map(fn (Achievement $achievement) => [
                ...$achievement->only(['key', 'name', 'description', 'icon_path']),
                'unlocked' => $unlockedKeys->contains($achievement->key),
            ]),
        ]);
    }
}
