<?php

namespace App\Services;

use App\Models\Theme;
use Illuminate\Support\Facades\Cache;

class ThemeService
{
    private const CACHE_KEY = 'active_theme';
    private const CACHE_TTL = 3600; // 1 hour

    /**
     * Get the currently active theme (cached)
     */
    public function getActiveTheme(): ?Theme
    {
        try {
            return Cache::remember(self::CACHE_KEY, self::CACHE_TTL, function () {
                return Theme::getActive();
            });
        } catch (\Throwable $e) {
            return null;
        }
    }

    /**
     * Apply a theme by ID
     */
    public function applyTheme(int $themeId): bool
    {
        $theme = Theme::findOrFail($themeId);
        
        $result = $theme->activate();
        
        if ($result) {
            Cache::forget(self::CACHE_KEY);
            Cache::put(self::CACHE_KEY, $theme, self::CACHE_TTL);
        }
        
        return $result;
    }

    /**
     * Get all available themes
     */
    public function getAllThemes()
    {
        return Theme::orderBy('name')->get();
    }

    /**
     * Get theme CSS variables for injection
     */
    public function getThemeCssVariables(): array
    {
        $theme = $this->getActiveTheme();
        
        if (!$theme) {
            return $this->getDefaultCssVariables();
        }
        
        return $theme->toCssVariables();
    }

    /**
     * Get default CSS variables when no theme is active
     */
    private function getDefaultCssVariables(): array
    {
        return [
            '--theme-primary' => '#3b82f6',
            '--theme-secondary' => '#64748b',
            '--theme-accent' => '#8b5cf6',
            '--theme-font-body' => 'Inter, sans-serif',
            '--theme-font-heading' => 'Inter, sans-serif',
            '--theme-color-body' => '#1f2937',
            '--theme-color-heading' => '#111827',
            '--theme-color-link' => '#3b82f6',
            '--theme-bg-body' => '#ffffff',
            '--theme-bg-card' => '#f9fafb',
            '--theme-bg-card-hero' => '#e5e7eb',
            '--theme-bg-sidebar' => '#1f2937',
            '--theme-bg-header' => '#ffffff',
            '--theme-bg-footer' => '#1f2937',
            '--theme-scrollbar-track' => '#f1f5f9',
            '--theme-scrollbar-thumb' => '#cbd5e1',
            '--theme-scrollbar-width' => '8px',
            '--theme-divider-color' => '#e5e7eb',
            '--theme-divider-style' => 'solid',
            '--theme-divider-width' => '1px',
            '--theme-heading-weight' => '600',
            '--theme-heading-spacing' => '0.05em',
        ];
    }
}
