<?php

declare(strict_types=1);

namespace Flowaxy\Support\Actions\Theme;

use Flowaxy\Support\Actions\ActionInterface;
use Flowaxy\Support\Services\ThemeService;
use Flowaxy\Support\Facades\Log;
use Exception;
use Throwable;

use function preg_match;

// Действие активации темы
final class ActivateThemeAction implements ActionInterface
{
    private ThemeService $themeService;

    public function __construct()
    {
        $this->themeService = new ThemeService();
    }

    public function execute(array $params = []): array
    {
        $themeSlug = $params['theme_slug'] ?? '';

        if (empty($themeSlug)) {
            return [
                'success' => false,
                'error' => 'Slug теми не вказано',
            ];
        }

        try {
            $result = $this->themeService->activate($themeSlug);

            if ($result) {
                return [
                    'success' => true,
                    'message' => 'Тему активовано',
                    'data' => ['theme_slug' => $themeSlug],
                ];
            }

            return [
                'success' => false,
                'error' => 'Не вдалося активувати тему',
            ];
        } catch (Throwable $e) {
            try {
                Log::Error('Помилка активації теми', ['exception' => $e, 'theme_slug' => $themeSlug]);
            } catch (Throwable $logError) {
                // Ignore logging errors
            }
            return [
                'success' => false,
                'error' => $e->getMessage(),
            ];
        }
    }

    public function validate(array $params): array
    {
        if (empty($params['theme_slug'])) {
            return [
                'valid' => false,
                'error' => 'Slug теми обов\'язковий',
            ];
        }

        $themeSlug = (string)$params['theme_slug'];
        if (!preg_match('/^[a-z0-9\-_]+$/i', $themeSlug)) {
            return [
                'valid' => false,
                'error' => 'Невірний формат slug теми',
            ];
        }

        return ['valid' => true];
    }

    public function getName(): string
    {
        return 'activate_theme';
    }

    public function getDescription(): string
    {
        return 'Активація теми';
    }
}
