<?php

namespace App\Services;

use Stripe\StripeClient;

/**
 * Service Stripe pour le marketplace (GdevStudio).
 * Utilise UNIQUEMENT config/marketplace.php (.env MARKETPLACE_STRIPE_*).
 * Non modifiable par le client via l'admin.
 */
class MarketplaceStripeService
{
    protected ?StripeClient $stripe = null;

    protected function getSecret(): ?string
    {
        return config('marketplace.stripe.secret');
    }

    protected function getKey(): ?string
    {
        return config('marketplace.stripe.key');
    }

    protected function getWebhookSecret(): ?string
    {
        return config('marketplace.stripe.webhook_secret');
    }

    public function __construct()
    {
        $key = $this->getSecret();
        if ($key) {
            $this->stripe = new StripeClient($key);
        }
    }

    public function isConfigured(): bool
    {
        return $this->stripe !== null && ! empty($this->getSecret());
    }

    public function createCheckoutSession(string $itemType, string $itemSlug, string $itemName, int $priceCents, string $successUrl, string $cancelUrl): array
    {
        if (! $this->isConfigured()) {
            return ['error' => 'Stripe marketplace non configuré sur cette instance.'];
        }

        if ($priceCents < 50) {
            return ['error' => 'Montant invalide pour le paiement.'];
        }

        try {
            $session = $this->stripe->checkout->sessions->create([
                'payment_method_types' => ['card'],
                'line_items' => [
                    [
                        'price_data' => [
                            'currency' => 'eur',
                            'product_data' => [
                                'name' => $itemName,
                                'description' => "Achat {$itemType} - {$itemName}",
                                'images' => [],
                            ],
                            'unit_amount' => $priceCents,
                        ],
                        'quantity' => 1,
                    ],
                ],
                'mode' => 'payment',
                'success_url' => $successUrl,
                'cancel_url' => $cancelUrl,
                'metadata' => [
                    'marketplace' => '1',
                    'item_type' => $itemType,
                    'item_slug' => $itemSlug,
                ],
            ]);
        } catch (\Throwable $e) {
            return ['error' => 'Stripe : '.$e->getMessage()];
        }

        return [
            'session_id' => $session->id,
            'url' => $session->url,
        ];
    }

    public function retrieveCheckoutSession(string $sessionId)
    {
        if (! $this->isConfigured()) {
            return null;
        }

        return $this->stripe->checkout->sessions->retrieve($sessionId);
    }

    public function constructWebhookEvent(string $payload, string $signature)
    {
        $secret = $this->getWebhookSecret();
        if (! $secret) {
            return null;
        }

        return \Stripe\Webhook::constructEvent(
            $payload,
            $signature,
            $secret
        );
    }
}
