<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Core\Response;
use App\Core\Validator;
use App\Repositories\MatchRepository;
use App\Services\AdvancedScoreSheetService;
use App\Services\FixtureService;
use App\Services\ScoreSheetService;

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

    public function store(): void
    {
        Auth::requireRole(['admin']);
        $data = Request::json();
        $errors = Validator::require($data, ['tournament_id', 'home_team_id', 'away_team_id']);
        if ($errors) {
            Response::error('Datos inválidos', 422, $errors);
            return;
        }
        Response::json((new MatchRepository())->create($data), 201);
    }

    public function generateFixture(array $params): void
    {
        Auth::requireRole(['admin']);
        Response::json((new FixtureService())->generateLeague((int) $params['id'], Request::json()['start_date'] ?? null), 201);
    }

    public function scoreState(array $params): void
    {
        Response::json((new ScoreSheetService())->state((int) $params['id']));
    }

    public function scoreEvent(array $params): void
    {
        $user = Auth::requireRole(['admin', 'delegate']);
        try {
            Response::json((new ScoreSheetService())->addEvent((int) $params['id'], Request::json(), $user), 201);
        } catch (\InvalidArgumentException $e) {
            Response::error($e->getMessage(), 422);
        }
    }

    public function advancedState(array $params): void
    {
        Response::json((new AdvancedScoreSheetService())->state((int) $params['id']));
    }

    public function rotation(array $params): void
    {
        $this->advanced($params, 'setRotation');
    }

    public function libero(array $params): void
    {
        $this->advanced($params, 'setLibero');
    }

    public function substitution(array $params): void
    {
        $this->advanced($params, 'substitute');
    }

    public function timeout(array $params): void
    {
        $this->advanced($params, 'timeout');
    }

    public function rally(array $params): void
    {
        $this->advanced($params, 'rally');
    }

    public function advancedSanction(array $params): void
    {
        $this->advanced($params, 'sanction');
    }

    public function signature(array $params): void
    {
        $this->advanced($params, 'sign');
    }

    private function advanced(array $params, string $method): void
    {
        $user = Auth::requireRole(['admin', 'delegate']);
        try {
            Response::json((new AdvancedScoreSheetService())->$method((int) $params['id'], Request::json(), $user), 201);
        } catch (\InvalidArgumentException $e) {
            Response::error($e->getMessage(), 422);
        }
    }
}
