<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Link;
use App\Enums\LinkStatus;
use App\Enums\PaymentStatus;
use GuzzleHttp\Client;

class PaymentsVerify extends Command
{
    protected $signature = 'payments:verify';
    protected $description = 'Vérifie les payments pending auprès de FedaPay';

    public function handle()
    {
        $client = new Client(['base_uri' => 'https://api.fedapay.com/v1/']);
        $links = Link::where('status', LinkStatus::Pending)->get();

        foreach ($links as $link) {
            try {
                $response = $client->get("payment_requests/{$link->feda_request_id}", [
                    'auth' => [config('services.fedapay.key'), config('services.fedapay.secret')]
                ]);

                $data = json_decode($response->getBody(), true);
                $status = $data['status'] ?? null;

                if ($status === PaymentStatus::Paid->value) {
                    // Mettre à jour payment et link
                    $link->payments()->updateOrCreate(
                        ['feda_payment_id' => $data['payments'][0]['id']],
                        [
                            'link_id'  => $link->id,
                            'amount'   => (int) round($data['payments'][0]['amount'] / 100),
                            'currency' => $data['currency'],
                            'status'   => PaymentStatus::Paid,
                            'paid_at'  => $data['payments'][0]['paid_at'],
                        ]
                    );
                    $link->update(['status' => LinkStatus::Paid]);
                }

            } catch (\Exception $e) {
                $this->error("Erreur pour link {$link->id}: {$e->getMessage()}");
                continue;
            }
        }

        $this->info('Vérification terminée.');
    }
}
