<?php

namespace App\Console\Commands;

use App\Models\MatchmakingQueue;
use App\Services\MatchmakingService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class RunMatchmaking extends Command
{
    protected $signature   = 'matchmaking:tick';
    protected $description = 'Process matchmaking queue — find and create matches';

    public function handle(MatchmakingService $service): int
    {
        $entries = MatchmakingQueue::where('status', 'searching')
            ->lockForUpdate()
            ->get();

        $matched = 0;
        $processed = [];

        foreach ($entries as $entry) {
            // Skip if this user was already matched in this tick
            if (in_array($entry->user_id, $processed)) {
                continue;
            }

            $match = DB::transaction(fn () => $service->tryMatch($entry->fresh()));

            if ($match) {
                $matched++;
                $processed[] = $entry->user_id;
                // Mark opponent as processed too
                $processed[] = $match->guest_id === $entry->user_id
                    ? $match->host_id
                    : $match->guest_id;

                $this->line("✅ Match created: #{$match->id} — {$match->host->username} vs {$match->guest->username}");
            }
        }

        $this->info("Tick done. Queue: {$entries->count()}, Matched: {$matched}");
        return Command::SUCCESS;
    }
}
