import {
  constructClaim,
  constructClaimKey,
  constructRangeRead,
  constructStore,
  ContractIssuer,
  GRead,
} from '@coinweb/contract-kit';
import { CwebRead } from '@coinweb/contract-kit/dist/types/operations/read';
import { toHex } from 'lib/shared';

import { rangeReadLimit } from '../settings';
import { LockedKey, MutexLockState } from '../types';

export const mutexLockKey = '_mutex_lock';

export const constructMutexLockFirstPart = () => [mutexLockKey];

export const constructMutexLockClaimKey = (lockId: string, timestamp: number) =>
  constructClaimKey(constructMutexLockFirstPart(), [timestamp, lockId]);

export const constructMutexLockClaim = ({
  fee,
  keys,
  locked,
  lockId,
  timestamp,
  processId,
}: {
  lockId: string;
  timestamp: number;
  locked: boolean;
  keys: LockedKey[];
  fee: bigint;
  processId: string;
}) =>
  constructClaim(
    constructMutexLockClaimKey(lockId, timestamp),
    { locked, keys, processId } satisfies MutexLockState,
    toHex(fee)
  );

export const constructMutexLockClaimStore = ({
  fee,
  keys,
  lockId,
  timestamp,
  processId,
  locked,
}: {
  fee: bigint;
  keys: LockedKey[];
  lockId: string;
  timestamp: number;
  processId: string;
  locked: boolean;
}) => constructStore(constructMutexLockClaim({ fee, keys, locked, lockId, timestamp, processId }));

export const constructMutexLockClaimRangeRead = (issuer: ContractIssuer): GRead<CwebRead> =>
  constructRangeRead(issuer, constructMutexLockFirstPart(), {}, rangeReadLimit);

// export const constructMutexLockClaimTake = (lockId: string, timestamp: number) =>
//   constructTake(constructMutexLockClaimKey(lockId, timestamp));
