<?php

namespace App\Domain\Website\Services;

use App\Domain\Shared\Models\Academy;
use App\Domain\Website\Models\WebsiteSetting;

class WebsiteSettingService
{
    public function getOrCreate(Academy $academy): WebsiteSetting
    {
        return WebsiteSetting::withoutGlobalScope('academy')
            ->firstOrCreate(
                ['academy_id' => $academy->id],
                [
                    'template' => 'bold_athletic',
                    'site_title' => $academy->name_ar,
                    'site_title_en' => $academy->name,
                ]
            );
    }

    public function update(Academy $academy, array $data): WebsiteSetting
    {
        $settings = $this->getOrCreate($academy);
        $settings->update($data);

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

        return $settings->fresh();
    }

    public function publish(Academy $academy): WebsiteSetting
    {
        $settings = $this->getOrCreate($academy);
        $settings->update([
            'is_published' => true,
            'published_at' => now(),
        ]);

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

        return $settings;
    }

    public function unpublish(Academy $academy): WebsiteSetting
    {
        $settings = $this->getOrCreate($academy);
        $settings->update(['is_published' => false]);

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

        return $settings;
    }
}
