<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\TxnLog;
use App\Http\Controllers\Homecontroller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CheckStkStatus extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'stk:check-status {--limit=50 : Maximum number of records to process}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check and update STK status for launched transactions';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $limit = $this->option('limit');

        // Get all TxnLog records with stk_status = 'Launched'
        $launchedTransactions = TxnLog::where('stk_status', 'Launched')
            ->whereNotNull('checkout_request_id')
            ->limit($limit)
            ->get();

        if ($launchedTransactions->isEmpty()) {
            $this->info('No launched transactions found to check.');
            return 0;
        }

        $this->info("Found {$launchedTransactions->count()} launched transactions to check.");

        $processed = 0;
        $updated = 0;
        $errors = 0;

        $homeController = new Homecontroller();

        foreach ($launchedTransactions as $txnLog) {
            try {
                $this->line("Processing checkout_request_id: {$txnLog->checkout_request_id}");

                // Create a mock request with the checkout_request_id
                $request = new Request();
                $request->merge(['checkoutRequestID' => $txnLog->checkout_request_id]);

                // Call the validateStkPush function
                $response = $homeController->validateStkPush($request);

                $processed++;

                if ($response->getData()->status_updated ?? false) {
                    $updated++;
                    $this->info("✓ Updated status for {$txnLog->checkout_request_id}");
                } else {
                    $this->line("  - No update needed for {$txnLog->checkout_request_id}");
                }

                // Add a small delay to avoid overwhelming the API
                usleep(100000); // 0.1 second delay

            } catch (\Exception $e) {
                $errors++;
                $this->error("✗ Error processing {$txnLog->checkout_request_id}: " . $e->getMessage());

                // Log the error
                Log::error('STK Status Check Error', [
                    'checkout_request_id' => $txnLog->checkout_request_id,
                    'error' => $e->getMessage(),
                    'trace' => $e->getTraceAsString()
                ]);
            }
        }

        $this->newLine();
        $this->info("Processing complete:");
        $this->line("  - Total processed: {$processed}");
        $this->line("  - Status updated: {$updated}");
        $this->line("  - Errors: {$errors}");

        return 0;
    }
}
