<?php

namespace App\Http\Controllers\MerchantAdmin;

use App\Http\Controllers\Concerns\ResolvesMerchantContext;
use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Product;
use App\Models\User;
use App\Support\CacheKeys;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\View\View;

class DashboardController extends Controller
{
    use ResolvesMerchantContext;

    public function index(Request $request): View
    {
        $merchantId = $this->merchantId($request);
        $merchant = $this->merchant($request);

        $stats = Cache::remember(
            CacheKeys::merchantDashboardStats($merchantId),
            now()->addMinutes(10),
            fn () => [
                'users' => User::query()->forMerchant($merchantId)->count(),
                'products' => Product::query()->forMerchant($merchantId)->count(),
                'orders' => Order::query()->forMerchant($merchantId)->count(),
                'pending_orders' => Order::query()->forMerchant($merchantId)->where('status', 'pending')->count(),
            ]
        );

        return view('merchant_admin.dashboard', [
            'merchant' => $merchant,
            'stats' => $stats,
            'cacheMeta' => [
                'store' => config('cache.default'),
                'ttl' => '10m',
            ],
        ]);
    }
}
