<?php

namespace App\Observers;

use Illuminate\Support\Facades\Cache;
use Mtc\ContentManager\Contracts\PageModel;
use Mtc\MercuryDataModels\User;

class PageObserver extends \Mtc\ContentManager\Observers\PageObserver
{
    #[\Override]
    public function saved(PageModel $page)
    {
        if (app()->runningUnitTests() !== true) {
            parent::saved($page);
        }
        $page->linkedMenuEntries()->get()
            ->each(fn ($menuEntry) => $menuEntry->save());

        Cache::forget(tenant('id') . "-content-page-" . $page->slug);
    }

    #[\Override]
    protected function attachUser(PageModel $page, $user_id)
    {
        $isSuperAdmin = false;
        if (!empty($user_id)) {
            $isSuperAdmin = User::query()->find($user_id)?->hasRole('mtc');
        }
        if (!$isSuperAdmin) {
            parent::attachUser($page, $user_id);
        }
    }
}
