import {
  BlockFilter,
  constructBlock,
  constructClaim,
  constructClaimKey,
  constructStore,
  constructTake,
  ContractIssuer,
} from '@coinweb/contract-kit';

import { MutexNotifyLockState } from '../types';

export const mutexBlockLockKey = '_mutex_block_lock';

export const constructMutexBlockLockClaimKey = (lockId: string) => constructClaimKey([mutexBlockLockKey], [lockId]);

export const constructMutexBlockLockClaim = ({ lockId, timestamp }: MutexNotifyLockState) =>
  constructClaim(constructMutexBlockLockClaimKey(lockId), { lockId, timestamp } satisfies MutexNotifyLockState, '0x0');

export const constructMutexBlockLockClaimStore = ({ lockId, timestamp }: MutexNotifyLockState) =>
  constructStore(constructMutexBlockLockClaim({ lockId, timestamp }));

export const constructMutexBlockLockClaimTake = (lockId: string) =>
  constructTake(constructMutexBlockLockClaimKey(lockId));

export const constructMutexLockBlockFilter = (lockId: string, issuer: ContractIssuer): BlockFilter => {
  const { first_part: first, second_part: second } = constructMutexBlockLockClaimKey(lockId);

  return {
    issuer,
    first,
    second,
  };
};

export const constructMutexLockBlock = (lockId: string, issuer: ContractIssuer) => {
  return constructBlock([constructMutexLockBlockFilter(lockId, issuer)]);
};
