<?php

namespace App\Domain\Website\Services;

use App\Domain\Organization\Models\Company;
use App\Domain\Website\Models\SiteContent;
use App\Domain\Website\Models\SiteStatistic;
use Illuminate\Support\Facades\Cache;

/**
 * Reads published website content (§150).
 *
 * The public site is read-mostly and unauthenticated, so content is cached and
 * invalidated whenever an editor saves.
 */
class SiteContentService
{
    private const CACHE_TTL = 600;

    public function company(): ?Company
    {
        return Cache::remember('site:company', self::CACHE_TTL, fn () => Company::query()->orderBy('id')->first());
    }

    /** @return array<string, mixed> key => value for one content group */
    public function group(string $group): array
    {
        $companyId = $this->company()?->id;

        if ($companyId === null) {
            return [];
        }

        return Cache::remember("site:content:{$companyId}:{$group}", self::CACHE_TTL, fn () => SiteContent::query()
            ->where('company_id', $companyId)
            ->where('group', $group)
            ->where('is_published', true)
            ->orderBy('sort_order')
            ->get()
            ->mapWithKeys(fn (SiteContent $content) => [$content->key => $content->resolvedValue()])
            ->all());
    }

    /** @return array<int, array<string, mixed>> */
    public function statistics(): array
    {
        $companyId = $this->company()?->id;

        if ($companyId === null) {
            return [];
        }

        return Cache::remember("site:stats:{$companyId}", self::CACHE_TTL, fn () => SiteStatistic::query()
            ->where('company_id', $companyId)
            ->where('is_published', true)
            ->orderBy('sort_order')
            ->get()
            ->map(fn (SiteStatistic $statistic) => [
                'key' => $statistic->key,
                'label' => $statistic->label,
                'value' => $statistic->value,
                'suffix' => $statistic->suffix,
                'icon' => $statistic->icon,
            ])
            ->all());
    }

    public function flush(): void
    {
        $companyId = $this->company()?->id;

        Cache::forget('site:company');

        if ($companyId === null) {
            return;
        }

        Cache::forget("site:stats:{$companyId}");

        foreach (['general', 'hero', 'about', 'contact', 'footer', 'seo', 'process'] as $group) {
            Cache::forget("site:content:{$companyId}:{$group}");
        }
    }
}
