<?php

namespace App\Http\Controllers;

use App\Models\MarketplacePurchase;
use App\Services\MarketplaceStripeService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class MarketplaceStripeWebhookController extends Controller
{
    public function __construct(
        protected MarketplaceStripeService $stripeService
    ) {}

    public function handle(Request $request)
    {
        $payload = $request->getContent();
        $sig = $request->header('Stripe-Signature', '');

        try {
            $event = $this->stripeService->constructWebhookEvent($payload, $sig);
        } catch (\Exception $e) {
            Log::warning('Marketplace Stripe webhook signature verification failed: '.$e->getMessage());

            return response()->json(['error' => $e->getMessage()], 400);
        }

        if ($event->type === 'checkout.session.completed') {
            $this->handleCheckoutSessionCompleted($event->data->object);
        }

        return response()->json(['received' => true]);
    }

    protected function handleCheckoutSessionCompleted(object $session): void
    {
        if (($session->metadata['marketplace'] ?? '') !== '1') {
            return;
        }

        $sessionId = $session->id;
        if (MarketplacePurchase::where('stripe_checkout_session_id', $sessionId)->exists()) {
            return;
        }

        $itemType = $session->metadata['item_type'] ?? null;
        $itemSlug = $session->metadata['item_slug'] ?? null;

        if (! $itemType || ! $itemSlug) {
            Log::warning('Marketplace Stripe checkout missing metadata', ['session_id' => $sessionId]);

            return;
        }

        MarketplacePurchase::create([
            'item_type' => $itemType,
            'item_slug' => $itemSlug,
            'license_key' => 'STRIPE-'.strtoupper(bin2hex(random_bytes(6))),
            'stripe_checkout_session_id' => $sessionId,
            'is_active' => true,
            'admin_enabled' => true,
            'purchased_at' => now(),
        ]);
    }
}
