<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\OnlinePlayer;
use App\Models\ServerHeartbeat;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ServerHeartbeatController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        $server = $request->attributes->get('fivem_server');

        $data = $request->validate([
            'player_count' => ['required', 'integer', 'min:0'],
            'max_players' => ['required', 'integer', 'min:0'],
            'resources' => ['nullable', 'array'],
            'players' => ['nullable', 'array'],
            'players.*.citizen_id' => ['nullable', 'string', 'max:100'],
            'players.*.name' => ['required_with:players', 'string', 'max:100'],
            'players.*.source_id' => ['required_with:players', 'integer'],
        ]);

        ServerHeartbeat::create([
            'fivem_server_id' => $server->id,
            'player_count' => $data['player_count'],
            'max_players' => $data['max_players'],
            'resources' => $data['resources'] ?? [],
            'recorded_at' => now(),
        ]);

        foreach ($data['players'] ?? [] as $player) {
            OnlinePlayer::query()->updateOrCreate(
                ['fivem_server_id' => $server->id, 'source_id' => $player['source_id']],
                [
                    'citizen_id' => $player['citizen_id'] ?? null,
                    'name' => $player['name'],
                    'updated_at' => now(),
                ]
            );
        }

        return response()->json(['status' => 'ok']);
    }
}
