<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\PlayerResource;
use App\Models\Player;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Validation\Rule;

class PlayerController extends Controller
{
    public function index(Request $request): ResourceCollection
    {
        $query = Player::with('team');

        if ($request->has('teamId')) {
            $query->where('team_id', $request->teamId);
        }

        return PlayerResource::collection($query->orderBy('number')->get());
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'teamId'   => 'required|exists:teams,id',
            'number'   => 'required|integer|min:1|max:99',
            'name'     => 'required|string|max:100',
            'position' => ['required', Rule::in(['GK', 'DEF', 'MID', 'FWD'])],
            'age'      => 'nullable|integer|min:15|max:50',
        ]);

        $player = Player::create([
            'team_id'  => $validated['teamId'],
            'number'   => $validated['number'],
            'name'     => $validated['name'],
            'position' => $validated['position'],
            'age'      => $validated['age'] ?? null,
        ]);

        return (new PlayerResource($player))->response()->setStatusCode(201);
    }

    public function update(Request $request, Player $player): PlayerResource
    {
        $validated = $request->validate([
            'teamId'       => 'sometimes|exists:teams,id',
            'number'       => 'sometimes|integer|min:1|max:99',
            'name'         => 'sometimes|string|max:100',
            'position'     => ['sometimes', Rule::in(['GK', 'DEF', 'MID', 'FWD'])],
            'age'          => 'nullable|integer|min:15|max:50',
            'yellowCards'  => 'sometimes|integer|min:0',
            'redCards'     => 'sometimes|integer|min:0',
            'goals'        => 'sometimes|integer|min:0',
            'assists'      => 'sometimes|integer|min:0',
            'matchesPlayed' => 'sometimes|integer|min:0',
        ]);

        $player->update(array_filter([
            'team_id'       => $validated['teamId'] ?? null,
            'number'        => $validated['number'] ?? null,
            'name'          => $validated['name'] ?? null,
            'position'      => $validated['position'] ?? null,
            'age'           => $validated['age'] ?? null,
            'yellow_cards'  => $validated['yellowCards'] ?? null,
            'red_cards'     => $validated['redCards'] ?? null,
            'goals'         => $validated['goals'] ?? null,
            'assists'       => $validated['assists'] ?? null,
            'matches_played' => $validated['matchesPlayed'] ?? null,
        ], fn ($v) => $v !== null));

        return new PlayerResource($player->fresh());
    }

    public function destroy(Player $player): JsonResponse
    {
        $player->delete();

        return response()->json(['message' => 'Player deleted.']);
    }
}
