<?php

namespace App\Http\Controllers\Tenant;

use App\Enums\PaymentStatus;
use App\Http\Controllers\Controller;
use App\Models\SubscriptionPayment;
use App\Services\Payment\PaymentManager;
use App\Support\Tenant;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class PaymentController extends Controller
{
    public function index(): View
    {
        $company = Tenant::current();

        return view('tenant.payments.index', [
            'company' => $company,
            'payments' => SubscriptionPayment::latest()->paginate(10),
            'drivers' => collect(config('payments.drivers'))->map(fn ($driver, $key) => [
                'key' => $key,
                'name' => $driver['name'],
                'enabled' => (bool) $driver['enabled'],
            ]),
        ]);
    }

    public function checkout(SubscriptionPayment $payment, PaymentManager $payments): RedirectResponse
    {
        $intent = $payments->driver($payment->driver)->createIntent($payment);

        $payment->update([
            'external_id' => $intent->externalId ?? $payment->external_id,
            'gateway_response' => $intent->payload,
        ]);

        if ($intent->redirectUrl) {
            return redirect()->away($intent->redirectUrl);
        }

        return back()->with('success', 'Intento de pago preparado. Completa la configuración de Wompi para redirigir al checkout.');
    }

    public function createPending(PaymentManager $payments): RedirectResponse
    {
        $company = Tenant::current();
        $subscription = $company?->activeSubscription;

        if (! $company || ! $subscription) {
            return back()->with('error', 'No hay una suscripción activa para generar pago.');
        }

        $payment = SubscriptionPayment::create([
            'subscription_id' => $subscription->id,
            'company_id' => $company->id,
            'reference' => config('payments.invoice_prefix', 'RES-').now()->format('YmdHis').'-'.$company->id,
            'driver' => config('payments.default_driver', 'manual'),
            'status' => PaymentStatus::Pending,
            'amount' => $subscription->amount,
            'currency' => $subscription->currency,
            'period_start' => $subscription->current_period_start,
            'period_end' => $subscription->current_period_end,
        ]);

        $intent = $payments->driver($payment->driver)->createIntent($payment);
        $payment->update(['gateway_response' => $intent->payload]);

        return back()->with('success', 'Pago pendiente creado.');
    }
}
