<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Recharge;
use App\Models\RechargeSetting;
use App\Services\SuccessTopupClient;
use App\Actions\RechargeFinalizer;

class RechargeSyncStatus extends Command
{
    protected $signature = 'recharge:sync-status {--limit=50}';
    protected $description = 'Sync pending recharges from SuccessTopup and finalize safely';

    public function handle(SuccessTopupClient $client, RechargeFinalizer $finalizer)
    {
        $setting = RechargeSetting::one();
        if (!$setting->api_key || !$setting->api_secret) {
            $this->info('No API key/secret.');
            return 0;
        }

        $rows = Recharge::where('status', 'pending')
            ->orderBy('id')
            ->limit((int)$this->option('limit'))
            ->get();

        if ($rows->isEmpty()) {
            $this->info('No pending.');
            return 0;
        }

        foreach ($rows as $r) {
            try {
                $lastResponseStatus = SuccessTopupClient::normalizeStatus(is_array($r->last_response) ? $r->last_response : []);
                if ($lastResponseStatus === 'success') {
                    $finalizer->markSuccess($r->id, is_array($r->last_response) ? $r->last_response : []);
                    $this->info("SUCCESS: {$r->tran_id} (last_response)");
                    continue;
                }

                if ($lastResponseStatus === 'failed') {
                    $finalizer->markFailed($r->id, is_array($r->last_response) ? $r->last_response : []);
                    $this->info("FAILED: {$r->tran_id} (last_response)");
                    continue;
                }

                $stRes = $client->status($setting->api_key, $setting->api_secret, $r->tran_id);
                Recharge::where('id', $r->id)->update(['last_response' => $stRes]);

                $st = SuccessTopupClient::normalizeStatus($stRes);

                if ($st === 'success') {
                    $finalizer->markSuccess($r->id, $stRes);
                    $this->info("SUCCESS: {$r->tran_id}");
                } elseif ($st === 'failed') {
                    $finalizer->markFailed($r->id, $stRes);
                    $this->info("FAILED: {$r->tran_id}");
                } else {
                    $this->info("PENDING: {$r->tran_id}");
                }
            } catch (\Throwable $e) {
                $this->error("ERR {$r->tran_id}: " . $e->getMessage());
            }
        }

        return 0;
    }
}
