<?php

namespace Modules\CashRegister\Observers;

use Modules\CashRegister\Entities\CashRegisterSession;
use Modules\CashRegister\Services\CashRegisterCacheService;

class CashRegisterSessionObserver
{
    /**
     * Handle the CashRegisterSession "created" event.
     */
    public function created(CashRegisterSession $session): void
    {
        // Clear session cache when new session is created
        CashRegisterCacheService::clearSessionCache($session->opened_by, $session->branch_id);
    }

    /**
     * Handle the CashRegisterSession "updated" event.
     */
    public function updated(CashRegisterSession $session): void
    {
        // Clear session cache when session is updated
        CashRegisterCacheService::clearSessionCache($session->opened_by, $session->branch_id);
        
        // Clear session totals cache
        CashRegisterCacheService::clearSessionTotalsCache($session->id);
        
        // Also clear if opened_by or branch_id changed
        if ($session->isDirty('opened_by')) {
            CashRegisterCacheService::clearSessionCache($session->getOriginal('opened_by'), $session->branch_id);
        }
        if ($session->isDirty('branch_id')) {
            CashRegisterCacheService::clearSessionCache($session->opened_by, $session->getOriginal('branch_id'));
        }
    }

    /**
     * Handle the CashRegisterSession "deleted" event.
     */
    public function deleted(CashRegisterSession $session): void
    {
        // Clear session cache when session is deleted
        CashRegisterCacheService::clearSessionCache($session->opened_by, $session->branch_id);
        CashRegisterCacheService::clearSessionTotalsCache($session->id);
    }
}

