<?php

namespace App\Jobs;

use App\Models\PaymentWebhookEvent;
use App\Models\User;
use App\Models\UserSubscription;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class ProcessPaymentWebhookJob implements ShouldQueue
{
    use Queueable;

    public function __construct(public string $eventId)
    {
    }

    public function handle(): void
    {
        $event = PaymentWebhookEvent::find($this->eventId);
        if (!$event) {
            return;
        }

        $payload = $event->payload ?? [];
        $email = data_get($payload, 'data.object.metadata.email')
            ?? data_get($payload, 'resource.payer.email_address');
        $plan = data_get($payload, 'data.object.metadata.plan');
        $paypalCustomId = data_get($payload, 'resource.purchase_units.0.custom_id');
        if (!$plan && is_string($paypalCustomId) && str_contains($paypalCustomId, '|')) {
            [, $plan] = explode('|', $paypalCustomId, 2);
        }
        $amount = (float) (data_get($payload, 'data.object.amount_total', 0) / 100);
        if ($amount <= 0) {
            $amount = (float) data_get($payload, 'resource.purchase_units.0.amount.value', 0);
        }
        $currency = strtoupper((string) (data_get($payload, 'data.object.currency')
            ?? data_get($payload, 'resource.purchase_units.0.amount.currency_code', 'USD')));

        if ($email && in_array($plan, ['starter', 'growth', 'pro'], true)) {
            $user = User::where('email', $email)->first();
            if ($user) {
                UserSubscription::create([
                    'user_id' => $user->id,
                    'plan' => $plan,
                    'period' => 'monthly',
                    'source' => $event->provider,
                    'transaction_id' => $event->event_id,
                    'receipt_data' => json_encode($payload),
                    'amount_paid' => $amount,
                    'currency' => $currency,
                    'is_active' => true,
                    'starts_at' => now(),
                    'expires_at' => now()->addMonth(),
                ]);

                $user->update([
                    'plan' => $plan,
                    'plan_source' => $event->provider,
                    'plan_expires_at' => now()->addMonth(),
                ]);
            }
        }

        $event->update([
            'status' => 'processed',
            'processed_at' => now(),
            'processing_notes' => 'Processed by queued webhook job.',
        ]);
    }
}
