<?php

namespace App\Console\Commands;

use App\Domain\Inventory\Models\Product;
use App\Domain\Notification\Services\NotificationService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class NotifyLowStock extends Command
{
    protected $signature = 'inventory:notify-low-stock';
    protected $description = 'Notify admins about products below minimum stock level';

    public function handle(NotificationService $notificationService): int
    {
        $lowStockProducts = Product::where('track_inventory', true)
            ->where('is_active', true)
            ->whereNotNull('min_stock_level')
            ->whereHas('inventoryLevels', function ($q) {
                $q->whereRaw('quantity_on_hand < (SELECT min_stock_level FROM products WHERE products.id = inventory_levels.product_id)');
            })
            ->with(['inventoryLevels', 'branch'])
            ->get();

        if ($lowStockProducts->isEmpty()) {
            $this->info('No low stock products found.');
            return self::SUCCESS;
        }

        $grouped = $lowStockProducts->groupBy('academy_id');

        foreach ($grouped as $academyId => $products) {
            $productList = $products->map(fn ($p) => "{$p->name_ar} ({$p->inventoryLevels->first()?->quantity_on_hand}/{$p->min_stock_level})")
                ->implode(', ');

            $admins = DB::table('users')
                ->where('academy_id', $academyId)
                ->where('status', 'active')
                ->whereIn('id', function ($q) {
                    $q->select('user_id')->from('role_user')
                        ->whereIn('role_id', function ($rq) {
                            $rq->select('id')->from('roles')->where('level', '>=', 70);
                        });
                })
                ->get();

            foreach ($admins as $admin) {
                try {
                    $notificationService->send(
                        eventType: 'low_stock_alert',
                        recipientType: 'user',
                        recipientId: $admin->id,
                        academyId: $academyId,
                        variables: [
                            'product_count' => (string) $products->count(),
                            'product_list' => $productList,
                        ],
                        recipientEmail: $admin->email,
                    );
                } catch (\Throwable $e) {
                    Log::warning("Low stock notification failed: " . $e->getMessage());
                }
            }

            $this->info("Notified admins for academy {$academyId}: {$products->count()} low-stock products.");
        }

        return self::SUCCESS;
    }
}
