<?php

namespace App\Domain\Website\Services;

use App\Domain\Shared\Models\Academy;
use App\Domain\Website\Enums\SectionKey;
use App\Domain\Website\Models\WebsiteSection;
use Illuminate\Support\Collection;

class WebsiteSectionService
{
    public function seedDefaults(Academy $academy): void
    {
        $order = SectionKey::defaultOrder();

        foreach ($order as $index => $key) {
            WebsiteSection::withoutGlobalScope('academy')->firstOrCreate(
                ['academy_id' => $academy->id, 'section_key' => $key->value],
                [
                    'title' => $key->label(),
                    'sort_order' => $index,
                    'is_enabled' => !in_array($key, [SectionKey::Schedule, SectionKey::News]),
                ]
            );
        }
    }

    public function getEnabled(Academy $academy): Collection
    {
        return WebsiteSection::withoutGlobalScope('academy')
            ->where('academy_id', $academy->id)
            ->where('is_enabled', true)
            ->orderBy('sort_order')
            ->get();
    }

    public function getAll(Academy $academy): Collection
    {
        return WebsiteSection::withoutGlobalScope('academy')
            ->where('academy_id', $academy->id)
            ->orderBy('sort_order')
            ->get();
    }

    public function reorder(Academy $academy, array $orderedKeys): void
    {
        foreach ($orderedKeys as $index => $key) {
            WebsiteSection::withoutGlobalScope('academy')
                ->where('academy_id', $academy->id)
                ->where('section_key', $key)
                ->update(['sort_order' => $index]);
        }

        app(WebsiteCacheService::class)->invalidate($academy->id);
    }

    public function toggle(WebsiteSection $section, bool $enabled): void
    {
        $section->update(['is_enabled' => $enabled]);
        app(WebsiteCacheService::class)->invalidate($section->academy_id);
    }

    public function updateContent(WebsiteSection $section, array $data): WebsiteSection
    {
        $section->update($data);
        app(WebsiteCacheService::class)->invalidate($section->academy_id);
        return $section->fresh();
    }
}
