<?php

namespace App\Jobs;

use App\Models\TopUp;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;
use Throwable;

class ProcessTopUp implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public TopUp $topUp;

    public int $tries = 3;
    public int $timeout = 30;

    public function __construct(TopUp $topUp)
    {
        $this->topUp = $topUp;
    }

    public function handle(): void
    {
        // 🔒 SAFETY CHECKS
        if (! $this->topUp->is_paid || $this->topUp->status !== 'paid') {
            return;
        }

        // 🔄 Mark as processing
        $this->topUp->update([
            'status' => 'processing',
        ]);

        try {
            // 📡 CALL TOP-UP API (x-www-form-urlencoded)
            $response = Http::asForm()
                ->timeout(20)
                ->post('https://top-up.api.zarsoft.net/raht-pay/api.php', [
                    'username' => config('services.topup.username'),
                    'password' => config('services.topup.password'),
                    'phone'    => $this->topUp->phone,
                    'amount'   => $this->topUp->amount,
                ]);

            // ❌ API-level failure
            if ($response->failed()) {
                throw new \Exception('Top-up API HTTP error');
            }

            // OPTIONAL: if API returns success flag
            // Adjust this based on real response
            if (
                $response->json('status') !== 'success'
                && !str_contains(strtolower($response->body()), 'success')
            ) {
                throw new \Exception('Top-up API rejected request: ' . $response->body());
            }

            // ✅ SUCCESS
            $this->topUp->update([
                'status' => 'completed',
                'external_ref' => $response->json('transaction_id')
                    ?? now()->timestamp,
            ]);

        } catch (Throwable $e) {

            // ❌ FAILURE
            $this->topUp->update([
                'status' => 'failed',
                'error_message' => $e->getMessage(),
            ]);

            throw $e; // allow retry
        }
    }
}
