<?php

namespace App\Http\Controllers;

use App\Models\Registration;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class ScoreboardController extends Controller
{
    public function index()
    {
        return view('scoreboard');
    }

    public function select(Request $request)
    {
        $request->validate(['registration_id' => 'required|exists:registrations,id']);
        Cache::put('scoreboard_selected_player', $request->registration_id, now()->endOfDay());
        return response()->json(['status' => 'ok']);
    }

    public function state()
    {
        $id = Cache::get('scoreboard_selected_player');

        if (!$id) {
            return response()->json(['player' => null, 'leaderboard' => $this->leaderboard()]);
        }

        $reg = Registration::with([
            'sessions' => fn($q) => $q->orderByDesc('play_date')->with('shots')
        ])->findOrFail($id);

        $todaySession = $reg->sessions->firstWhere('play_date', today()->toDateString());
        $shots = $todaySession
            ? $todaySession->shots->sortBy('shot_number')->map(fn($s) => (bool)$s->result)->values()->toArray()
            : [];

        $history = $reg->sessions->map(fn($s) => [
            'date'  => $s->play_date,
            'score' => $s->score,
            'shots' => $s->shots->sortBy('shot_number')->map(fn($sh) => (bool)$sh->result)->values()->toArray(),
        ])->toArray();

        return response()->json([
            'player' => [
                'id'            => $reg->id,
                'name'          => $reg->name,
                'total_score'   => $reg->total_score,
                'shots'         => $shots,
                'session_score' => $todaySession?->calculateScore() ?? 0,
                'history'       => $history,
            ],
            'leaderboard' => $this->leaderboard(),
        ]);
    }

    private function leaderboard(): array
    {
        return Registration::orderByDesc('total_score')
            ->limit(5)
            ->get(['id', 'name', 'total_score'])
            ->map(fn($r, $i) => [
                'rank'        => $i + 1,
                'id'          => $r->id,
                'name'        => $r->name,
                'total_score' => $r->total_score,
            ])
            ->toArray();
    }
}