<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Product;
use App\Models\Bid;
use App\Models\Notification;
use App\Models\ProductLike;
use Carbon\Carbon;

class AuctionStartingAlert extends Command
{
    protected $signature = 'auction:starting-alert';
    protected $description = 'Send notification to favorite users before auction starts';

    public function handle()
    {
        $environment_data = getEnvironmentData();  
        $auction_starting_soon_notification_time_hours = $environment_data['AUCTION_STARTING_SOON_NOTIFICATION_TIME'];

        // Convert HH:MM to minutes
        if ($auction_starting_soon_notification_time_hours && str_contains($auction_starting_soon_notification_time_hours, ':')) {
            [$hours, $minutes] = explode(':', $auction_starting_soon_notification_time_hours);
            $alertBeforeMinutes = ($hours * 60) + $minutes; 
        } else {
            // Default 30 minutes
            $alertBeforeMinutes = 30;
        }

        $now = Carbon::now('UTC')->format('Y-m-d H:i');

        // LIVE DATE MUST MATCH: now + alertBeforeMinutes
        $targetLiveDate = Carbon::parse($now)->addMinutes($alertBeforeMinutes)->format('Y-m-d H:i');

        // $targetLiveDate = '2025-12-17 10:00:00'; // For testing purpose

        // Fetch products whose auction will start after X minutes
        $products = Product::where('status', 'Approved')
            ->where('is_sell', 0)
            ->where('product_type', 1)
            ->where('live_date', '=', $targetLiveDate)
            ->get();

        foreach ($products as $product) {
            // Only users who have added this product to favorites
            $favoriteUsers = ProductLike::select('user_id')
                ->where('product_sku', $product->sku)
                ->distinct()
                ->get();

            foreach ($favoriteUsers as $fav) {

                $message = "Auction for '{$product->name}' is about to start soon! Get ready.";

                // Save Notification
                Notification::create([
                    'user_id' => $fav->user_id,
                    'title'   => "Auction starting soon",
                    'message' => $message
                ]);

                // Push notification
                $data = pushNotification($fav->user_id, $message);
            }
        }

        return Command::SUCCESS;
    }
}