<?php

namespace App\Modules\Inventory\Stock\Repositories;

use App\Modules\Inventory\Stock\Models\InventoryStockIdempotencyKey;

class InventoryStockIdempotencyRepository
{
    public function findLocked(int $tenantId, string $key, string $source): ?InventoryStockIdempotencyKey
    {
        return InventoryStockIdempotencyKey::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
    {
        InventoryStockIdempotencyKey::withoutGlobalScopes()->create([
            'tenant_id' => $tenantId,
            'idempotency_key' => $key,
            'idempotency_source' => $source,
            'first_movement_id' => $movementId,
            'result_payload' => $payload,
        ]);
    }
}
