<?php

namespace App\Observers;

use App\Models\MenuItem;
use App\Services\Pos\MenuItemsCatalogCache;
use App\Services\Pos\PosTaxonomyCache;

class MenuItemObserver
{

    public function creating(MenuItem $menuItem)
    {
        if (branch()) {
            $menuItem->branch_id = branch()->id;
        }
    }

    public function saved(MenuItem $menuItem): void
    {
        MenuItemsCatalogCache::forgetForBranch($menuItem->branch_id);
        PosTaxonomyCache::bumpBranch($menuItem->branch_id);

        if ($menuItem->wasChanged('branch_id')) {
            $previousBranchId = $menuItem->getOriginal('branch_id');
            if ($previousBranchId) {
                MenuItemsCatalogCache::forgetForBranch((int) $previousBranchId);
                PosTaxonomyCache::bumpBranch((int) $previousBranchId);
            }
        }
    }

    public function deleted(MenuItem $menuItem): void
    {
        MenuItemsCatalogCache::forgetForBranch($menuItem->branch_id);
        PosTaxonomyCache::bumpBranch($menuItem->branch_id);
    }

}
