<?php

namespace App\Console\Commands;

use App\Models\Order;
use App\Services\EasyKashService;
use App\User;
use Illuminate\Console\Command;

class EasyKashPingCommand extends Command
{
    protected $signature = 'easykash:ping {--user-id=} {--amount=1} {--currency=EGP}';

    protected $description = 'Smoke-test EasyKash Pay API credentials (creates a payment link, does not complete payment)';

    public function handle(EasyKashService $easyKashService): int
    {
        $apiKey = trim((string) (config('services.easykash.api_key') ?: env('EASYKASH_API_KEY')));
        if ($apiKey === '') {
            $this->error('EASYKASH_API_KEY is not set in .env');

            return 1;
        }

        $userId = $this->option('user-id') ?: User::query()->value('id');
        $user = User::find($userId);

        if (!$user) {
            $this->error('No user found for ping test. Pass --user-id=');

            return 1;
        }

        $order = new Order([
            'id' => 999999,
            'total_amount' => (float) $this->option('amount'),
            'amount' => (float) $this->option('amount'),
            'currency' => strtoupper((string) $this->option('currency')),
        ]);

        try {
            $url = $easyKashService->createDirectPayLink($order, $user);
            $this->info('EasyKash API OK. Payment URL:');
            $this->line($url);

            return 0;
        } catch (\Throwable $e) {
            $this->error('EasyKash API failed: ' . $e->getMessage());

            return 1;
        }
    }
}
