<?php

namespace App\Modules\Inventory\Reservation\Repositories;

use App\Modules\Inventory\Reservation\Models\InventoryReservationIdempotencyKey;

class InventoryReservationIdempotencyRepository
{
    public function findLocked(int $tenantId, string $key, string $source): ?InventoryReservationIdempotencyKey
    {
        return InventoryReservationIdempotencyKey::withoutGlobalScopes()
            ->where('tenant_id', $tenantId)
            ->where('idempotency_key', $key)
            ->where('idempotency_source', $source)
            ->lockForUpdate()
            ->first();
    }

    /**
     * @param  array<string, mixed>  $payload
     */
    public function store(int $tenantId, string $key, string $source, int $movementId, array $payload): void
    {
        InventoryReservationIdempotencyKey::withoutGlobalScopes()->create([
            'tenant_id' => $tenantId,
            'idempotency_key' => $key,
            'idempotency_source' => $source,
            'first_reservation_movement_id' => $movementId,
            'result_payload' => $payload,
        ]);
    }
}
