<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Core\Response;
use App\Core\Validator;
use App\Repositories\PlayerRepository;
use App\Repositories\TeamRepository;

final class PlayerController
{
    public function index(): void
    {
        Response::json((new PlayerRepository())->all());
    }

    public function store(): void
    {
        Auth::requireRole(['admin', 'delegate']);
        $this->createFromData(Request::json());
    }

    public function registerByLink(array $params): void
    {
        $team = (new TeamRepository())->findByToken($params['token']);
        if (!$team) {
            Response::error('Link de equipo inválido', 404);
            return;
        }
        $data = Request::json();
        $data['team_id'] = $team['id'];
        $this->createFromData($data);
    }

    private function createFromData(array $data): void
    {
        $errors = Validator::require($data, ['team_id', 'first_name', 'last_name', 'document_id']);
        if ($errors) {
            Response::error('Datos inválidos', 422, $errors);
            return;
        }
        Response::json((new PlayerRepository())->create($data), 201);
    }
}
