import {
  constructClaim,
  constructClaimKey,
  constructContractIssuer,
  constructRangeRead,
  constructStore,
  Context,
  getContractId,
  GRead,
} from '@coinweb/contract-kit';
import { CwebRead } from '@coinweb/contract-kit/dist/esm/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,
  locked,
  lockId,
  timestamp,
  processId,
}: {
  fee: bigint;
  keys: LockedKey[];
  locked: boolean;
  lockId: string;
  timestamp: number;
  processId: string;
}) => constructStore(constructMutexLockClaim({ fee, keys, locked, lockId, timestamp, processId }));

export const constructMutexLockClaimRangeRead = (context: Context): GRead<CwebRead> =>
  constructRangeRead(
    constructContractIssuer(getContractId(context.tx)),
    constructMutexLockFirstPart(),
    {},
    rangeReadLimit
  );

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