<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\Auction\AuctionService;
use App\Models\AuctionVehicle;
use App\Models\Bid;
use Carbon\Carbon;

class SyncJapanAuctionsCommand extends Command
{
    protected $signature = 'auction:sync';
    protected $description = 'Synchronize live auctions from Japanese auction provider API';

    public function handle(AuctionService $auctionService): int
    {
        $this->info('Starting Japanese Auction Synchronization...');
        $provider = $auctionService->getProvider();

        // 1. Fetch live lots from provider
        $liveLots = $provider->getLiveAuctions();
        $this->info("Fetched " . count($liveLots) . " auction vehicles from provider.");

        // 2. Check and advance expired auctions
        $expiredVehicles = AuctionVehicle::whereIn('status', ['upcoming', 'live'])
            ->where('auction_ends_at', '<=', Carbon::now())
            ->get();

        foreach ($expiredVehicles as $vehicle) {
            $this->line("Processing closing lot #{$vehicle->lot_number} ({$vehicle->full_name})...");
            
            // Check top approved bid
            $winningBid = Bid::where('auction_vehicle_id', $vehicle->id)
                ->whereIn('status', ['submitted', 'bidding', 'approved'])
                ->orderBy('max_bid_jpy', 'desc')
                ->first();

            if ($winningBid) {
                $hammerPrice = min($winningBid->max_bid_jpy, $vehicle->starting_bid_jpy + 250000);
                $auctionService->markBidAsWon($winningBid, $hammerPrice, 'Auction concluded and lot won.');
                $this->info("  -> Won by Customer #{$winningBid->user_id} at ¥" . number_format($hammerPrice, 0));
            } else {
                $vehicle->update([
                    'status' => 'ended',
                    'result_status' => 'passed',
                ]);
                $this->line("  -> Lot passed or no customer bids placed.");
            }
        }

        $this->info('Japanese Auction Sync complete.');
        return Command::SUCCESS;
    }
}
