<?php

namespace App\Services\Payments;

use App\Models\Payment;
use App\Models\PaymentGateway;
use App\Models\SubscriptionPlan;
use App\Models\User;
use Illuminate\Http\Request;
use InvalidArgumentException;

class PaymentManagerService
{
    public function __construct(
        private readonly PaystackPaymentService $paystack,
        private readonly MonnifyPaymentService $monnify,
        private readonly FlutterwavePaymentService $flutterwave,
        private readonly StripePaymentService $stripe,
    ) {
    }

    public function activeGateway(): ?PaymentGateway
    {
        return PaymentGateway::query()
            ->active()
            ->orderBy('priority')
            ->orderBy('name')
            ->first();
    }

    public function activeConfiguredGateway(): ?PaymentGateway
    {
        return PaymentGateway::query()
            ->active()
            ->whereNotNull('secret_key')
            ->where('secret_key', '!=', '')
            ->orderBy('priority')
            ->orderBy('name')
            ->first();
    }

    public function initializePayment(User $user, SubscriptionPlan $plan, Payment $payment): array
    {
        $gateway = $payment->gateway ?: $this->activeConfiguredGateway();

        if (! $gateway) {
            return [
                'success' => false,
                'message' => 'Payment gateway is not available right now.',
            ];
        }

        return $this->serviceFor($gateway)->initializePayment($user, $plan, $gateway, $payment);
    }

    public function verifyPayment(PaymentGateway $gateway, string $reference): array
    {
        return $this->serviceFor($gateway)->verifyPayment($gateway, $reference);
    }

    public function handleWebhook(PaymentGateway $gateway, Request $request): array
    {
        return $this->serviceFor($gateway)->handleWebhook($gateway, $request);
    }

    private function serviceFor(PaymentGateway $gateway): PaystackPaymentService|MonnifyPaymentService|FlutterwavePaymentService|StripePaymentService
    {
        return match ($gateway->slug) {
            'paystack' => $this->paystack,
            'monnify' => $this->monnify,
            'flutterwave' => $this->flutterwave,
            'stripe' => $this->stripe,
            default => throw new InvalidArgumentException("Unsupported payment gateway: {$gateway->slug}"),
        };
    }
}
