<?php

namespace App\Domains\Purchase\Services\Checkout;

use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Services\PurchaseStateGuard;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class EditCheckoutService
{
    public function __construct(
        private readonly PurchaseResponseLoader $responses,
        private readonly PurchaseStateGuard $purchaseState,
    ) {}

    /** @param array<string, string> $customerData */
    public function updateCustomer(Purchase $purchase, array $customerData): Purchase
    {
        return DB::transaction(function () use ($purchase, $customerData): Purchase {
            /** @var Purchase $purchase */
            $purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
            $this->purchaseState->assertNotExpired($purchase);

            if (! in_array($purchase->status, [
                Purchase::STATUS_CREATED,
                Purchase::STATUS_PENDING_PAYMENT,
            ], true)) {
                throw ValidationException::withMessages([
                    'purchase' => __('api.purchase.not_editable'),
                ]);
            }

            $this->purchaseState->lockCurrentCart($purchase);

            $purchase->update($customerData);

            return $this->responses->load($purchase);
        });
    }
}
