<?php

namespace App\Services\Checkout;

use App\Models\CheckoutSession;
use App\Models\Package;
use App\Models\Tenant;
use App\Models\TenantPackage;
use App\Services\Coupons\CouponRedemptionService;
use App\Services\GiftVouchers\GiftVoucherService;
use App\Services\Paddle\PaddleSubscriptionService;
use Carbon\Carbon;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class CheckoutWebhookService
{
    public function __construct(
        private readonly CheckoutSessionService $sessions,
        private readonly CheckoutAssignmentService $assignment,
        private readonly PaddleSubscriptionService $paddleSubscriptions,
        private readonly CouponRedemptionService $couponRedemptions,
        private readonly GiftVoucherService $giftVouchers,
    ) {}

    public function handlePaddleEvent(array $event): bool
    {
        $eventType = $event['event_type'] ?? null;
        $data = $event['data'] ?? [];

        if (! $eventType || ! is_array($data)) {
            return false;
        }

        if (Str::startsWith($eventType, 'subscription.')) {
            return $this->handlePaddleSubscriptionEvent($eventType, $data);
        }

        if ($this->isGiftVoucherEvent($data)) {
            if ($eventType === 'transaction.completed') {
                $this->giftVouchers->issueFromPaddle($data);

                return true;
            }

            return in_array($eventType, ['transaction.processing', 'transaction.created', 'transaction.failed', 'transaction.cancelled'], true);
        }

        $session = $this->locatePaddleSession($data);

        if (! $session) {
            Log::info('[CheckoutWebhook] Paddle session not resolved', [
                'event_type' => $eventType,
                'transaction_id' => $data['id'] ?? null,
            ]);

            return false;
        }

        $transactionId = $data['id'] ?? $data['transaction_id'] ?? null;
        $lockKey = 'checkout:webhook:paddle:'.($transactionId ?: $session->id);
        $lock = Cache::lock($lockKey, 30);

        if (! $lock->get()) {
            Log::info('[CheckoutWebhook] Paddle lock busy', [
                'transaction_id' => $transactionId,
                'session_id' => $session->id,
            ]);

            return true;
        }

        try {
            if ($transactionId) {
                $session->forceFill([
                    'paddle_transaction_id' => $transactionId,
                    'provider' => CheckoutSession::PROVIDER_PADDLE,
                ])->save();
            } elseif ($session->provider !== CheckoutSession::PROVIDER_PADDLE) {
                $session->forceFill(['provider' => CheckoutSession::PROVIDER_PADDLE])->save();
            }

            $metadata = [
                'paddle_last_event' => $eventType,
                'paddle_transaction_id' => $transactionId,
                'paddle_status' => $data['status'] ?? null,
                'paddle_last_update_at' => now()->toIso8601String(),
            ];

            if (! empty($data['checkout_id'])) {
                $metadata['paddle_checkout_id'] = $data['checkout_id'];
            }

            $this->mergeProviderMetadata($session, $metadata);

            return $this->applyPaddleEvent($session, $eventType, $data);
        } finally {
            $lock->release();
        }
    }

    protected function applyPaddleEvent(CheckoutSession $session, string $eventType, array $data): bool
    {
        $status = strtolower((string) ($data['status'] ?? ''));

        switch ($eventType) {
            case 'transaction.created':
            case 'transaction.processing':
                $this->sessions->markProcessing($session, [
                    'paddle_status' => $status ?: null,
                ]);

                return true;

            case 'transaction.completed':
                $this->syncSessionTotals($session, $data);
                if ($session->status !== CheckoutSession::STATUS_COMPLETED) {
                    $this->sessions->markProcessing($session, [
                        'paddle_status' => $status ?: 'completed',
                    ]);

                    $this->assignment->finalise($session, [
                        'source' => 'paddle_webhook',
                        'provider' => CheckoutSession::PROVIDER_PADDLE,
                        'provider_reference' => $data['id'] ?? null,
                        'payload' => $data,
                    ]);

                    $this->sessions->markCompleted($session, now());
                    $this->couponRedemptions->recordSuccess($session, $data);
                }

                return true;

            case 'transaction.failed':
            case 'transaction.cancelled':
                $reason = $status ?: ($eventType === 'transaction.failed' ? 'paddle_failed' : 'paddle_cancelled');
                $this->sessions->markFailed($session, $reason);
                $this->couponRedemptions->recordFailure($session, $reason);

                return true;

            default:
                return false;
        }
    }

    protected function syncSessionTotals(CheckoutSession $session, array $data): void
    {
        $totals = $this->normalizePaddleTotals($data);

        if ($totals === []) {
            return;
        }

        $updates = [];

        if (array_key_exists('subtotal', $totals)) {
            $updates['amount_subtotal'] = $totals['subtotal'];
        }

        if (array_key_exists('discount', $totals)) {
            $updates['amount_discount'] = $totals['discount'];
        }

        if (array_key_exists('total', $totals)) {
            $updates['amount_total'] = $totals['total'];
        }

        if (! empty($totals['currency'])) {
            $updates['currency'] = $totals['currency'];
        }

        if ($updates !== []) {
            $session->forceFill($updates)->save();
        }

        $this->mergeProviderMetadata($session, [
            'paddle_totals' => $totals,
        ]);
    }

    /**
     * @return array{currency?: string, subtotal?: float, discount?: float, tax?: float, total?: float}
     */
    protected function normalizePaddleTotals(array $data): array
    {
        $totals = Arr::get($data, 'details.totals', Arr::get($data, 'totals', []));
        $currency = Arr::get($totals, 'currency_code')
            ?? $data['currency_code'] ?? Arr::get($totals, 'currency') ?? Arr::get($data, 'currency');

        $subtotal = $this->convertMinorAmount(Arr::get($totals, 'subtotal.amount', $totals['subtotal'] ?? null));
        $discount = $this->convertMinorAmount(Arr::get($totals, 'discount.amount', $totals['discount'] ?? null));
        $tax = $this->convertMinorAmount(Arr::get($totals, 'tax.amount', $totals['tax'] ?? null));
        $total = $this->convertMinorAmount(
            Arr::get(
                $totals,
                'total.amount',
                $totals['total'] ?? Arr::get($totals, 'grand_total.amount', $totals['grand_total'] ?? null)
            )
        );

        return array_filter([
            'currency' => $currency ? strtoupper((string) $currency) : null,
            'subtotal' => $subtotal,
            'discount' => $discount,
            'tax' => $tax,
            'total' => $total,
        ], static fn ($value) => $value !== null);
    }

    protected function convertMinorAmount(mixed $value): ?float
    {
        if ($value === null || $value === '') {
            return null;
        }

        if (is_array($value) && isset($value['amount'])) {
            $value = $value['amount'];
        }

        if (! is_numeric($value)) {
            return null;
        }

        return round(((float) $value) / 100, 2);
    }

    protected function handlePaddleSubscriptionEvent(string $eventType, array $data): bool
    {
        $subscriptionId = $data['id'] ?? null;

        if (! $subscriptionId) {
            return false;
        }

        $customData = $this->extractCustomData($data);
        $tenant = $this->resolveTenantFromSubscription($data, $customData, $subscriptionId);

        if (! $tenant) {
            Log::info('[CheckoutWebhook] Paddle subscription tenant not resolved', [
                'subscription_id' => $subscriptionId,
            ]);

            return false;
        }

        $package = $this->resolvePackageFromSubscription($data, $customData, $subscriptionId);

        if (! $package) {
            Log::info('[CheckoutWebhook] Paddle subscription package not resolved', [
                'subscription_id' => $subscriptionId,
            ]);

            return false;
        }

        $status = strtolower((string) ($data['status'] ?? ''));
        $expiresAt = $this->resolveSubscriptionExpiry($data);
        $startedAt = $this->resolveSubscriptionStart($data);

        $tenantPackage = TenantPackage::firstOrNew([
            'tenant_id' => $tenant->id,
            'package_id' => $package->id,
        ]);

        $tenantPackage->fill([
            'paddle_subscription_id' => $subscriptionId,
            'price' => $package->price,
        ]);

        $tenantPackage->expires_at = $expiresAt ?? $tenantPackage->expires_at ?? $startedAt?->copy()->addYear();
        $tenantPackage->purchased_at = $tenantPackage->purchased_at
            ?? $tenant->purchases()->where('package_id', $package->id)->latest('purchased_at')->value('purchased_at')
            ?? $startedAt;

        $tenantPackage->active = $this->isSubscriptionActive($status);
        $tenantPackage->save();

        if ($eventType === 'subscription.cancelled' || $eventType === 'subscription.paused') {
            $tenantPackage->forceFill(['active' => false])->save();
        }

        $tenant->forceFill([
            'subscription_status' => $this->mapSubscriptionStatus($status),
            'subscription_expires_at' => $expiresAt,
            'paddle_customer_id' => $tenant->paddle_customer_id ?: ($data['customer_id'] ?? null),
        ])->save();

        Log::info('[CheckoutWebhook] Paddle subscription event processed', [
            'tenant_id' => $tenant->id,
            'package_id' => $package->id,
            'subscription_id' => $subscriptionId,
            'event_type' => $eventType,
            'status' => $status,
        ]);

        return true;
    }

    protected function resolveTenantFromSubscription(array $data, array $metadata, string $subscriptionId): ?Tenant
    {
        if (isset($metadata['tenant_id'])) {
            $tenant = Tenant::find((int) $metadata['tenant_id']);
            if ($tenant) {
                return $tenant;
            }
        }

        $customerId = $data['customer_id'] ?? null;

        if ($customerId) {
            $tenant = Tenant::where('paddle_customer_id', $customerId)->first();
            if ($tenant) {
                return $tenant;
            }
        }

        $subscription = $this->paddleSubscriptions->retrieve($subscriptionId);
        $customerId = Arr::get($subscription, 'data.customer_id');

        if ($customerId) {
            return Tenant::where('paddle_customer_id', $customerId)->first();
        }

        return null;
    }

    protected function resolvePackageFromSubscription(array $data, array $metadata, string $subscriptionId): ?Package
    {
        if (isset($metadata['package_id'])) {
            $package = Package::withTrashed()->find((int) $metadata['package_id']);
            if ($package) {
                return $package;
            }
        }

        $priceId = Arr::get($data, 'items.0.price_id') ?? Arr::get($data, 'items.0.price.id');

        if ($priceId) {
            $package = Package::withTrashed()->where('paddle_price_id', $priceId)->first();
            if ($package) {
                return $package;
            }
        }

        $subscription = $this->paddleSubscriptions->retrieve($subscriptionId);
        $priceId = Arr::get($subscription, 'data.items.0.price_id') ?? Arr::get($subscription, 'data.items.0.price.id');

        if ($priceId) {
            return Package::withTrashed()->where('paddle_price_id', $priceId)->first();
        }

        return null;
    }

    protected function resolveSubscriptionExpiry(array $data): ?Carbon
    {
        $nextBilling = Arr::get($data, 'next_billing_date') ?? Arr::get($data, 'next_payment_date');

        if ($nextBilling) {
            return Carbon::parse($nextBilling);
        }

        $endsAt = Arr::get($data, 'billing_period_ends_at') ?? Arr::get($data, 'pays_out_at');

        return $endsAt ? Carbon::parse($endsAt) : null;
    }

    protected function resolveSubscriptionStart(array $data): Carbon
    {
        $created = Arr::get($data, 'created_at') ?? Arr::get($data, 'activated_at');

        return $created ? Carbon::parse($created) : now();
    }

    protected function isSubscriptionActive(string $status): bool
    {
        return in_array($status, ['active', 'trialing'], true);
    }

    protected function mapSubscriptionStatus(string $status): string
    {
        return match ($status) {
            'active', 'trialing' => 'active',
            'paused' => 'suspended',
            'cancelled', 'past_due', 'halted' => 'expired',
            default => 'free',
        };
    }

    protected function mergeProviderMetadata(CheckoutSession $session, array $data): void
    {
        $session->provider_metadata = array_merge($session->provider_metadata ?? [], $data);
        $session->save();
    }

    protected function isGiftVoucherEvent(array $data): bool
    {
        $metadata = $this->extractCustomData($data);

        $type = is_array($metadata) ? ($metadata['type'] ?? $metadata['kind'] ?? $metadata['category'] ?? null) : null;

        if ($type && in_array(strtolower($type), ['gift_card', 'gift_voucher'], true)) {
            return true;
        }

        $priceId = $data['price_id'] ?? Arr::get($metadata, 'paddle_price_id');
        $tiers = collect(config('gift-vouchers.tiers', []))
            ->pluck('paddle_price_id')
            ->filter()
            ->all();

        return $priceId && in_array($priceId, $tiers, true);
    }

    protected function locatePaddleSession(array $data): ?CheckoutSession
    {
        $metadata = $this->extractCustomData($data);

        if (is_array($metadata)) {
            $sessionId = $metadata['checkout_session_id'] ?? null;

            if ($sessionId && $session = CheckoutSession::find($sessionId)) {
                return $session;
            }

            $tenantId = $metadata['tenant_id'] ?? null;
            $packageId = $metadata['package_id'] ?? null;

            if ($tenantId && $packageId) {
                $session = CheckoutSession::query()
                    ->where('tenant_id', $tenantId)
                    ->where('package_id', $packageId)
                    ->whereNotIn('status', [CheckoutSession::STATUS_COMPLETED, CheckoutSession::STATUS_CANCELLED])
                    ->latest()
                    ->first();

                if ($session) {
                    return $session;
                }
            }
        }

        $checkoutId = $data['checkout_id'] ?? Arr::get($data, 'details.checkout_id');

        if ($checkoutId) {
            return CheckoutSession::query()
                ->where('provider_metadata->paddle_checkout_id', $checkoutId)
                ->first();
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function extractCustomData(array $data): array
    {
        $customData = [];

        if (isset($data['custom_data']) && is_array($data['custom_data'])) {
            $customData = $data['custom_data'];
        }

        if (isset($data['customData']) && is_array($data['customData'])) {
            $customData = array_merge($customData, $data['customData']);
        }

        if (isset($data['metadata']) && is_array($data['metadata'])) {
            $customData = array_merge($customData, $data['metadata']);
        }

        return $customData;
    }
}
