<?php

namespace App\Domains\Cart\Services;

use App\Domains\Auth\Models\User;
use App\Domains\Cart\Models\Cart;
use Illuminate\Support\Facades\DB;

class GuestCartMergeService
{
    public function merge(string $tenantCodigo, User $user, ?string $guestToken): void
    {
        if ($guestToken === null || $guestToken === '') {
            return;
        }

        DB::transaction(function () use ($tenantCodigo, $user, $guestToken): void {
            $guestCart = Cart::query()
                ->where('tenant_codigo', $tenantCodigo)
                ->where('guest_token', $guestToken)
                ->where('status', 'active')
                ->lockForUpdate()
                ->first();

            if ($guestCart === null || ! $guestCart->items()->exists()) {
                return;
            }

            $userCart = Cart::query()
                ->where('tenant_codigo', $tenantCodigo)
                ->where('user_id', $user->getKey())
                ->where('status', 'active')
                ->lockForUpdate()
                ->first();

            if ($userCart !== null) {
                $userCart->items()
                    ->orderBy('id')
                    ->pluck('id')
                    ->each(fn (int $itemId) => $userCart->removeItem($itemId));
                $userCart->update([
                    'status' => 'converted',
                ]);
                $userCart->delete();
            }

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