<?php

namespace App\Http\Middleware;

use App\Models\Cart;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

class MergeGuestCart
{
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        // Only merge if user just logged in
        if ($request->user() && $request->routeIs('auth.login')) {
            $this->mergeGuestCart($request);
        }

        return $response;
    }

    protected function mergeGuestCart(Request $request): void
    {
        $user = $request->user();
        $sessionId = $request->session()->getId();
        $guestUuid = $request->cookie('guest_uuid');

        // Get guest cart
        $guestCart = Cart::where(function ($query) use ($sessionId, $guestUuid) {
            $query->where('session_id', $sessionId)
                  ->orWhere('guest_uuid', $guestUuid);
        })->whereNull('user_id')->first();

        if (! $guestCart) {
            return;
        }

        // Get or create user cart
        $userCart = Cart::firstOrCreate(
            ['user_id' => $user->id],
            ['expires_at' => now()->addDays(30)]
        );

        // Merge cart items
        foreach ($guestCart->items as $guestItem) {
            $existingItem = $userCart->items()
                ->where('product_id', $guestItem->product_id)
                ->where('product_variant_id', $guestItem->product_variant_id)
                ->first();

            if ($existingItem) {
                // Update quantity
                $existingItem->increment('quantity', $guestItem->quantity);
            } else {
                // Create new item
                $userCart->items()->create([
                    'product_id' => $guestItem->product_id,
                    'product_variant_id' => $guestItem->product_variant_id,
                    'quantity' => $guestItem->quantity,
                    'price' => $guestItem->price,
                ]);
            }
        }

        // Delete guest cart
        $guestCart->delete();
    }
}
