<?php

namespace App\Console\Commands;

use App\Models\Transaction;
use Illuminate\Console\Command;

class AutoCloseTransactions extends Command
{
    protected $signature = 'transactions:auto-close';

    protected $description = 'Complete pending transactions whose auto_close_at deadline has passed without buyer confirmation';

    public function handle(): int
    {
        $closed = 0;

        Transaction::pending()
            ->whereNotNull('auto_close_at')
            ->where('auto_close_at', '<=', now())
            ->each(function (Transaction $transaction) use (&$closed) {
                $transaction->update([
                    'status' => 'completed',
                    'completed_at' => now(),
                ]);
                $closed++;
            });

        $this->info("Auto-closed {$closed} transaction(s).");

        return self::SUCCESS;
    }
}
