<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Core\Response;
use App\Core\Validator;
use App\Repositories\SheetTemplateRepository;

final class SheetTemplateController
{
    public function index(): void
    {
        Auth::requireRole(['admin']);
        Response::json((new SheetTemplateRepository())->all());
    }

    public function store(): void
    {
        Auth::requireRole(['admin']);
        $data = Request::json();
        $errors = Validator::require($data, ['code', 'name', 'image_path', 'page_width', 'page_height', 'config_json']);
        if ($errors) {
            Response::error('Datos invalidos', 422, $errors);
            return;
        }
        Response::json((new SheetTemplateRepository())->create($data), 201);
    }

    public function show(array $params): void
    {
        Auth::requireRole(['admin']);
        $template = (new SheetTemplateRepository())->find((int) $params['id']);
        Response::json($template ?: ['message' => 'No encontrado'], $template ? 200 : 404);
    }

    public function effective(array $params): void
    {
        Auth::requireRole(['admin']);
        $repo = new SheetTemplateRepository();
        $template = $repo->find((int) $params['id']);
        if (!$template) {
            Response::error('No encontrado', 404);
            return;
        }
        $template['effective_config_json'] = json_encode($repo->effectiveConfig($template), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        Response::json($template);
    }

    public function update(array $params): void
    {
        Auth::requireRole(['admin']);
        $template = (new SheetTemplateRepository())->update((int) $params['id'], Request::json());
        Response::json($template ?: ['message' => 'No encontrado'], $template ? 200 : 404);
    }

    public function assignTournament(array $params): void
    {
        Auth::requireRole(['admin']);
        (new SheetTemplateRepository())->assignToTournament((int) $params['id'], (int) Request::json()['sheet_template_id']);
        Response::json(['assigned' => true]);
    }

    public function overrideMatch(array $params): void
    {
        Auth::requireRole(['admin']);
        (new SheetTemplateRepository())->overrideMatch((int) $params['id'], (int) Request::json()['sheet_template_id']);
        Response::json(['assigned' => true]);
    }
}
