<?php

namespace App\Modules\Procurement\Repositories;

use App\Modules\Procurement\Models\GoodsReceiptPostIdempotencyKey;

class GoodsReceiptPostIdempotencyRepository
{
    public function findLocked(int $tenantId, string $key, string $source): ?GoodsReceiptPostIdempotencyKey
    {
        return GoodsReceiptPostIdempotencyKey::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 $goodsReceiptId, array $payload): void
    {
        GoodsReceiptPostIdempotencyKey::withoutGlobalScopes()->create([
            'tenant_id' => $tenantId,
            'idempotency_key' => $key,
            'idempotency_source' => $source,
            'goods_receipt_id' => $goodsReceiptId,
            'result_payload' => $payload,
        ]);
    }
}
