<?php

namespace App\Domains\Purchase\Services\Checkout;

use App\Domains\Cart\Models\Cart;
use App\Domains\Purchase\Models\Purchase;

class SourceCartService
{
    public function finalize(Purchase $purchase): void
    {
        $sourceCart = $this->findSourceCart($purchase);

        if ($sourceCart === null || $sourceCart->trashed()) {
            return;
        }

        $sourceCart->update([
            'status' => 'converted',
            'guest_token' => null,
        ]);
        $sourceCart->delete();
    }

    private function findSourceCart(Purchase $purchase): ?Cart
    {
        if ($purchase->cart_id === null) {
            return null;
        }

        /** @var Cart|null */
        return Cart::withTrashed()
            ->whereKey($purchase->cart_id)
            ->lockForUpdate()
            ->first();
    }
}
