<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\WhatsappTemplate;

class TemplateService
{
    private WhatsappTemplate $templateModel;

    public function __construct()
    {
        $this->templateModel = new WhatsappTemplate();
    }

    public function getTemplates(array $filters = [], int $page = 1, int $perPage = 20): array
    {
        return $this->templateModel->findWithPagination($page, $perPage, $filters);
    }

    public function getTemplate(int $id): array
    {
        $template = $this->templateModel->findById($id);
        if (!$template) {
            throw new \RuntimeException('Plantilla no encontrada', 404);
        }

        if ($template['variables']) {
            $template['variables'] = json_decode($template['variables'], true);
        }

        return $template;
    }

    public function createTemplate(array $data, int $userId): array
    {
        if (empty($data['name'])) {
            throw new \RuntimeException('El nombre es obligatorio', 422);
        }
        if (empty($data['content'])) {
            throw new \RuntimeException('El contenido es obligatorio', 422);
        }

        $variables = $this->extractVariables($data['content']);

        $id = $this->templateModel->create([
            'name' => $data['name'],
            'content' => $data['content'],
            'variables' => !empty($variables) ? json_encode($variables) : null,
            'created_by' => $userId,
        ]);

        return $this->getTemplate($id);
    }

    public function updateTemplate(int $id, array $data): array
    {
        $template = $this->templateModel->findById($id);
        if (!$template) {
            throw new \RuntimeException('Plantilla no encontrada', 404);
        }

        $updateData = [];
        foreach (['name', 'content'] as $field) {
            if (array_key_exists($field, $data)) {
                $updateData[$field] = $data[$field];
            }
        }

        if (isset($updateData['content'])) {
            $variables = $this->extractVariables($updateData['content']);
            $updateData['variables'] = !empty($variables) ? json_encode($variables) : null;
        }

        if (!empty($updateData)) {
            $this->templateModel->update($id, $updateData);
        }

        return $this->getTemplate($id);
    }

    public function deleteTemplate(int $id): void
    {
        $template = $this->templateModel->findById($id);
        if (!$template) {
            throw new \RuntimeException('Plantilla no encontrada', 404);
        }

        $this->templateModel->delete($id);
    }

    public function validateVariables(string $content): array
    {
        $variables = $this->extractVariables($content);
        return [
            'valid' => true,
            'variables' => $variables,
        ];
    }

    private function extractVariables(string $content): array
    {
        preg_match_all('/\{([a-zA-Z_]+)\}/', $content, $matches);
        return array_unique($matches[1] ?? []);
    }
}
