<?php

namespace App\Helpers\FirstParty\Credits;

use App\Helpers\FirstParty\Stripe\StripeHelper;
use App\Models\PaymentWebhookProcessedLog;
use Laravel\Cashier\Events\WebhookReceived;

class UserCreditHelper
{
    public static function handleStripeWebhook(WebhookReceived $event)
    {
        $payload = $event->payload;

        switch ($payload['type']) {
            case 'checkout.session.completed':
                self::handleCheckoutSessionCompleted($payload['data']['object']);
                break;
        }
    }

    private static function handleCheckoutSessionCompleted($checkout_session)
    {
        // Check if the webhook has already been processed
        $payment_webhook_processed_log = PaymentWebhookProcessedLog::where('provider', 'stripe')
            ->where('log_id', $checkout_session['id'])
            ->where('log_type', 'checkout_session')
            ->first();

        if (! is_null($payment_webhook_processed_log)) {
            return;
        }

        // Get the user associated with the checkout session
        $user = StripeHelper::getUserByStripeCustomerId($checkout_session['customer']);

        if ($user) {

            // Get the line items from the checkout session
            $lineItems = \Stripe\Checkout\Session::allLineItems($checkout_session['id']);

            foreach ($lineItems->data as $lineItem) {
                $stripe_price_id = $lineItem->price->id;
                $stripe_product_id = $lineItem->price->product;

                // Get the credit pack associated with the price ID
                $credit_pack = CreditsHelper::getCreditPackByStripePriceId($stripe_product_id, $stripe_price_id, get_stripe_env());

                if (is_null($credit_pack)) {
                    continue;
                }

                $total_credits = $credit_pack['purchased_credits'] + $credit_pack['bonus_credits'];

                // Deposit the credits to the user's account
                CreditsService::depositAlacarte($user->id, $total_credits, "Purchased {$credit_pack['name']}");
            }
        }

        // Mark the webhook as processed
        PaymentWebhookProcessedLog::create([
            'provider' => 'stripe',
            'log_id' => $checkout_session['id'],
            'log_type' => 'checkout_session',
        ]);
    }
}
