<?php

namespace App\Console\Commands;

use App\Models\Product;
use App\Models\ProductVersion;
use App\Models\User;
use App\Notifications\ProductVersionUpdateNotification;
use Illuminate\Console\Command;

class CheckProductVersionUpdates extends Command
{
    protected $signature = 'products:check-version-updates';
    protected $description = 'Notify users when newer base solution versions are available for their products';

    public function handle(): int
    {
        // Fetch products with a selected base version
        $products = Product::with(['baseProductVersion', 'category'])
            ->whereNotNull('base_product_version_id')
            ->get();

        foreach ($products as $product) {
            if (!$product->category) {
                continue;
            }

            $latest = ProductVersion::where('status', 'published')
                ->where('category_id', $product->category_id)
                ->orderByDesc('created_at')
                ->first();

            $current = $product->baseProductVersion;
            if (!$latest || !$current) {
                continue;
            }

            $shouldUpdate = version_compare($latest->version, $current->version, '>') ||
                ($latest->version === $current->version && $latest->updated_at->gt($current->updated_at));

            if (!$shouldUpdate) {
                continue;
            }

            // Decide who to notify: here we notify all users; adjust to your actual user subset
            // foreach (\App\Models\User::all() as $user) {
            //     $user->notify(new ProductVersionUpdateNotification($product, $current, $latest));
            // }
            $users = User::whereNotNull('email_verified')->get();
            // echo "Notifying " . $users->count() . " users about update for product {$product->name}\n";
            foreach ($users as $user) {
                $user->notify(new ProductVersionUpdateNotification($product, $current, $latest));
            }
        }

        $this->info('Product version update check complete.');
        return self::SUCCESS;
    }
}
