<?php

namespace Modules\MultiPOS\Services;

use Modules\MultiPOS\Entities\PosMachine;
use Illuminate\Support\Facades\Cache;

class PosMachineCacheService
{
    const CACHE_TTL = 300; // 5 minutes
    const MACHINE_CACHE_TTL = 60; // 1 minute

    /**
     * Get active machine by device ID (cached)
     */
    public static function getActiveMachineByDeviceId(string $deviceId, int $branchId): ?PosMachine
    {
        $cacheKey = "multipos.machine.device.{$deviceId}.{$branchId}";
        
        return Cache::remember($cacheKey, self::MACHINE_CACHE_TTL, function () use ($deviceId, $branchId) {
            return PosMachine::where('device_id', $deviceId)
                ->where('branch_id', $branchId)
                ->where('status', 'active')
                ->first();
        });
    }

    /**
     * Clear machine cache
     */
    public static function clearMachineCache(?string $deviceId = null, ?int $branchId = null): void
    {
        if ($deviceId && $branchId) {
            Cache::forget("multipos.machine.device.{$deviceId}.{$branchId}");
        } else {
            // Clear all machine caches (would need cache tags for proper implementation)
            // For now, clear specific patterns
        }
    }

    /**
     * Get machines for branch (cached)
     */
    public static function getBranchMachines(int $branchId): \Illuminate\Database\Eloquent\Collection
    {
        $cacheKey = "multipos.machines.branch.{$branchId}";
        
        return Cache::remember($cacheKey, self::CACHE_TTL, function () use ($branchId) {
            return PosMachine::where('branch_id', $branchId)
                ->orderBy('registered_at', 'desc')
                ->get();
        });
    }

    /**
     * Clear branch machines cache
     */
    public static function clearBranchMachinesCache(int $branchId): void
    {
        Cache::forget("multipos.machines.branch.{$branchId}");
    }

    /**
     * Get machine count for branch (cached)
     */
    public static function getBranchMachineCount(int $branchId, ?string $status = null): int
    {
        $cacheKey = "multipos.machine.count.branch.{$branchId}";
        if ($status) {
            $cacheKey .= ".{$status}";
        }
        
        return Cache::remember($cacheKey, self::CACHE_TTL, function () use ($branchId, $status) {
            $query = PosMachine::where('branch_id', $branchId);
            if ($status) {
                $query->where('status', $status);
            }
            return $query->count();
        });
    }

    /**
     * Clear machine count cache
     */
    public static function clearMachineCountCache(int $branchId): void
    {
        Cache::forget("multipos.machine.count.branch.{$branchId}");
        Cache::forget("multipos.machine.count.branch.{$branchId}.active");
        Cache::forget("multipos.machine.count.branch.{$branchId}.pending");
        Cache::forget("multipos.machine.count.branch.{$branchId}.declined");
    }
}

