<?php

namespace App\Listeners;

use App\Models\Cart;
use Illuminate\Auth\Events\Login;

/**
 * A shopper who added items while browsing as a guest shouldn't lose them
 * by logging in. Folds the session-keyed guest cart into the user's cart,
 * summing quantities where the same variant appears in both.
 */
class MergeGuestCartOnLogin
{
    public function handle(Login $event): void
    {
        $guestCart = Cart::whereNull('user_id')
            ->where('session_id', session()->getId())
            ->with('items')
            ->first();

        if (! $guestCart || $guestCart->items->isEmpty()) {
            return;
        }

        $userCart = Cart::firstOrCreate(['user_id' => $event->user->getAuthIdentifier()]);

        foreach ($guestCart->items as $guestItem) {
            $existing = $userCart->items()
                ->where('product_variant_id', $guestItem->product_variant_id)
                ->first();

            if ($existing) {
                $existing->increment('quantity', $guestItem->quantity);
                $guestItem->delete();
            } else {
                $guestItem->update(['cart_id' => $userCart->id]);
            }
        }

        $guestCart->delete();
    }
}
