<?php

namespace App\Services;

use App\Models\AppearanceSetting;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;

class AppearanceService
{
    private ?array $store = null;

    private function cacheKey(): string
    {
        return config('appearance.cache_key', 'appearance_settings');
    }

    private function ttl(): int
    {
        return config('appearance.cache_ttl', 86400);
    }

    private function load(): array
    {
        if ($this->store !== null) {
            return $this->store;
        }

        $cached = Cache::get($this->cacheKey());

        if ($cached !== null) {
            return $this->store = $cached;
        }

        try {
            if (! Schema::hasTable('appearance_settings')) {
                return $this->store = [];
            }

            $activeTheme = setting('site_theme', 'tailwind');

            $rows = AppearanceSetting::query()
                ->where(function ($q) use ($activeTheme) {
                    $q->whereNull('theme_slug')
                      ->orWhere('theme_slug', $activeTheme);
                })
                ->get();

            $map = [];
            foreach ($rows as $row) {
                $map[$row->key] = $row->value ?? $row->default_value;
            }

            Cache::put($this->cacheKey(), $map, $this->ttl());

            return $this->store = $map;
        } catch (\Throwable) {
            return $this->store = [];
        }
    }

    public function get(string $key, mixed $fallback = null): mixed
    {
        return $this->load()[$key] ?? $fallback;
    }

    public function set(string $key, mixed $value): void
    {
        $activeTheme = setting('site_theme', 'tailwind');

        AppearanceSetting::where('key', $key)
            ->where(function ($q) use ($activeTheme) {
                $q->whereNull('theme_slug')
                  ->orWhere('theme_slug', $activeTheme);
            })
            ->update(['value' => $value]);

        $this->flush();
    }

    public function setMany(array $values): void
    {
        $activeTheme = setting('site_theme', 'tailwind');

        foreach ($values as $key => $value) {
            AppearanceSetting::where('key', $key)
                ->where(function ($q) use ($activeTheme) {
                    $q->whereNull('theme_slug')
                      ->orWhere('theme_slug', $activeTheme);
                })
                ->update(['value' => $value]);
        }

        $this->flush();
    }

    public function flush(): void
    {
        $this->store = null;
        Cache::forget($this->cacheKey());
        $activeTheme = setting('site_theme', 'tailwind');
        Cache::forget(config('appearance.css_cache_key', 'appearance_css') . '_' . $activeTheme);
    }
}
