<?php

namespace App\Modules\Navigation\Services;

use App\Models\User;
use App\Modules\Procurement\Models\GoodsReceipt;
use App\Modules\Procurement\Models\PurchaseOrder;
use App\Modules\Sales\Models\SalesOrder;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;

/**
 * Lightweight queue/draft counts for mega menu badges (cached per user).
 */
final class NavigationMegaMenuSignalService
{
    private const TTL_SECONDS = 90;

    /**
     * @return array{badges: array<string, int>}
     */
    public function forUser(User $user): array
    {
        if ($user->tenant_id === null || (int) $user->tenant_id <= 0 || $user->isAdmin()) {
            return ['badges' => []];
        }

        return Cache::remember(
            $this->cacheKey($user),
            self::TTL_SECONDS,
            fn (): array => $this->build($user),
        );
    }

    public static function forgetForUser(User $user): void
    {
        Cache::forget(self::staticCacheKey($user));
    }

    /**
     * @return array{badges: array<string, int>}
     */
    private function build(User $user): array
    {
        $tid = (int) $user->tenant_id;
        $badges = [];

        if ($user->can('procurement.purchase_orders.view') && Route::has('procurement.purchase-orders.index')) {
            $n = PurchaseOrder::query()->where('tenant_id', $tid)->where('status', 'draft')->count();
            if ($n > 0) {
                $badges['procurement.purchase-orders.index'] = $n;
            }
        }
        if ($user->can('procurement.goods_receipts.view') && Route::has('procurement.goods-receipts.index')) {
            $n = GoodsReceipt::query()->where('tenant_id', $tid)->where('status', 'draft')->count();
            if ($n > 0) {
                $badges['procurement.goods-receipts.index'] = $n;
            }
        }
        if ($user->can('sales.orders.view') && Route::has('sales.orders.index')) {
            $n = SalesOrder::query()->where('tenant_id', $tid)->where('status', 'draft')->count();
            if ($n > 0) {
                $badges['sales.orders.index'] = $n;
            }
        }

        $queue = array_sum($badges);
        if ($queue > 0 && Route::has('operations.workflow-inbox.index')
            && (
                $user->can('operations.control.view')
                || $user->can('leave.view')
                || $user->can('attendance.view')
                || $user->can('procurement.purchase_orders.view')
                || $user->can('procurement.goods_receipts.view')
                || $user->can('sales.orders.view')
            )) {
            $badges['operations.workflow-inbox.index'] = $queue;
        }

        return ['badges' => $badges];
    }

    private function cacheKey(User $user): string
    {
        return self::staticCacheKey($user);
    }

    private static function staticCacheKey(User $user): string
    {
        return 'navigation:mega_signals:user:'.$user->id.':tenant:'.($user->tenant_id ?? '0');
    }
}
