<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Helpers\Response;
use App\Services\TemplateService;

class TemplateController extends BaseController
{
    private TemplateService $templateService;

    public function __construct($request)
    {
        parent::__construct($request);
        $this->templateService = new TemplateService();
    }

    public function index(): void
    {
        $filters = [
            'search' => $this->request->query('search'),
            'status' => $this->request->query('status'),
        ];
        $page = (int) ($this->request->query('page', 1));
        $perPage = (int) ($this->request->query('per_page', 20));

        $result = $this->templateService->getTemplates($filters, $page, $perPage);

        Response::paginated($result['items'], $result['total'], $result['page'], $result['per_page'], 'Plantillas consultadas correctamente');
    }

    public function show(): void
    {
        $id = (int) $this->getRouteParam('id');
        try {
            $template = $this->templateService->getTemplate($id);
            Response::success($template, 'Plantilla consultada correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function store(): void
    {
        $data = $this->request->body();

        $validation = $this->validate($data, function ($v) {
            $v->required('name', 'Nombre');
            $v->required('content', 'Contenido');
        });

        if ($validation->fails()) {
            Response::error($validation->firstError(), 422);
        }

        try {
            $template = $this->templateService->createTemplate($data, $this->getAuthUserId());
            Response::created($template, 'Plantilla creada correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function update(): void
    {
        $id = (int) $this->getRouteParam('id');
        $data = $this->request->body();

        try {
            $template = $this->templateService->updateTemplate($id, $data);
            Response::success($template, 'Plantilla actualizada correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function destroy(): void
    {
        $id = (int) $this->getRouteParam('id');

        try {
            $this->templateService->deleteTemplate($id);
            Response::success(null, 'Plantilla eliminada correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function validateVariables(): void
    {
        $data = $this->request->body();

        if (empty($data['content'])) {
            Response::error('El contenido es obligatorio', 422);
        }

        $result = $this->templateService->validateVariables($data['content']);
        Response::success($result, 'Variables extraídas correctamente');
    }
}
