<?php

namespace App\Listeners;

use App\Models\Order;
use App\Models\Product;
use Laravel\Cashier\Events\WebhookReceived;

/**
 * Records one-off guest purchases when Stripe confirms payment.
 * Subscription lifecycle is handled by Cashier itself.
 */
class StripeEventListener
{
    public function handle(WebhookReceived $event): void
    {
        if ($event->payload['type'] !== 'checkout.session.completed') {
            return;
        }

        $session = $event->payload['data']['object'];

        if (($session['mode'] ?? null) !== 'payment') {
            return;
        }

        $order = Order::firstOrCreate(
            ['stripe_checkout_session_id' => $session['id']],
            [
                'email' => $session['customer_details']['email'] ?? 'unknown',
                'name' => $session['customer_details']['name'] ?? null,
                'stripe_payment_intent_id' => $session['payment_intent'] ?? null,
                'amount_total' => $session['amount_total'] ?? 0,
                'currency' => $session['currency'] ?? config('farmpilot.currency'),
                'status' => $session['payment_status'] ?? 'paid',
            ],
        );

        if ($order->wasRecentlyCreated && ($productId = $session['metadata']['product_id'] ?? null)) {
            $product = Product::find($productId);

            $order->items()->create([
                'product_id' => $product?->id,
                'name' => $product?->name ?? 'Product',
                'quantity' => (int) ($session['metadata']['quantity'] ?? 1),
                'amount' => $session['amount_total'] ?? 0,
            ]);
        }
    }
}
