<?php

namespace App\Domains\Cart\Middleware;

use App\Domains\Cart\Models\Cart;
use App\Domains\Tenant\Models\Tenant;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Symfony\Component\HttpFoundation\Response;

class MergeGuestCartMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        $guestToken = $request->cookie('guest_token');

        // Resolve authenticated user optionally (from default guard or sanctum guard)
        $user = $request->user() ?? Auth::guard('sanctum')->user();
        $userId = $user?->getKey();

        \Illuminate\Support\Facades\Log::info('MergeGuestCartMiddleware processed', [
            'user_id' => $userId,
            'guest_token' => $guestToken,
        ]);

        if ($user !== null && is_string($guestToken) && $guestToken !== '') {
            $tenantParam = $request->route('tenant');
            $tenantCodigo = null;

            if ($tenantParam instanceof Tenant) {
                $tenantCodigo = $tenantParam->codigo;
            } elseif (is_string($tenantParam)) {
                $tenantCodigo = $tenantParam;
            }

            if ($tenantCodigo !== null) {
                $guestCart = Cart::query()
                    ->where('tenant_codigo', $tenantCodigo)
                    ->where('guest_token', $guestToken)
                    ->first();

                if ($guestCart !== null && $guestCart->items()->exists()) {
                    $userCart = Cart::query()
                        ->where('tenant_codigo', $tenantCodigo)
                        ->where('user_id', $userId)
                        ->first();

                    if ($userCart !== null) {
                        $userCart->delete();
                    }

                    $guestCart->update([
                        'user_id' => $userId,
                        'guest_token' => null,
                    ]);
                }
            }
        }

        $response = $next($request);

        if ($user !== null && is_string($guestToken) && $guestToken !== '') {
            // Remove the cookie from the response since the user is authenticated.
            if (method_exists($response, 'withCookie')) {
                $response->withCookie(Cookie::forget('guest_token'));
            }
        }

        return $response;
    }
}
