<?php

namespace App\Listeners;

use App\Enums\FaqCategory;
use App\Enums\MenuLocation;
use App\Events\ModelChanged;
use App\Models\Announcement;
use App\Models\Category;
use App\Models\Comment;
use App\Models\Course;
use App\Models\CourseSchedule;
use App\Models\Faq;
use App\Models\GuideCard;
use App\Models\HeroSlide;
use App\Models\Menu;
use App\Models\Page;
use App\Models\Setting;
use Illuminate\Support\Facades\Cache;

class ClearModelCache
{
    /**
     * Map of model classes to their cache key prefixes.
     *
     * @var array<class-string, list<string>>
     */
    private const CACHE_KEYS = [
        Category::class => ['categories'],
        Course::class => ['courses', 'categories'],
        CourseSchedule::class => ['schedules', 'courses'],
        Announcement::class => ['announcements'],
        HeroSlide::class => ['hero_slides'],
        Menu::class => ['menus'],
        Comment::class => ['comments'],
        Faq::class => ['faqs'],
        GuideCard::class => ['guide_cards'],
        Setting::class => ['settings'],
        Page::class => ['pages'],
    ];

    /**
     * Handle the event.
     */
    public function handle(ModelChanged $event): void
    {
        $keys = self::CACHE_KEYS[$event->modelClass] ?? [];

        foreach ($keys as $prefix) {
            Cache::forget($prefix);

            // Clear sub-keyed caches (e.g., menus.header_main, faqs.egitimler)
            if ($prefix === 'menus') {
                foreach (MenuLocation::cases() as $location) {
                    Cache::forget("menus.{$location->value}");
                }
            }

            if ($prefix === 'faqs') {
                foreach (FaqCategory::cases() as $category) {
                    Cache::forget("faqs.{$category->value}");
                }
            }
        }
    }
}
