import {
  BlockFilter,
  constructBlock,
  constructClaim,
  constructClaimKey,
  constructRead,
  constructStore,
  constructTake,
  ContractIssuer,
  CwebStore,
  GStore,
} from '@coinweb/contract-kit';
import { toHex } from 'lib/shared';

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

export const mutexExecOpsKey = '_mutex_exec_ops';

export const constructMutexExecOpsClaimKey = (execId: string) => constructClaimKey([mutexExecOpsKey], [execId]);

export const constructMutexExecOpsClaim = (execId: string, result: MutexExecOpsResult, storeCweb: bigint) =>
  constructClaim(constructMutexExecOpsClaimKey(execId), result, toHex(storeCweb));

export const constructMutexExecOpsClaimStore = (
  execId: string,
  result: MutexExecOpsResult,
  storeCweb: bigint = 0n
): GStore<CwebStore> => constructStore(constructMutexExecOpsClaim(execId, result, storeCweb));

export const constructMutexExecOpsClaimRead = (issuer: ContractIssuer, execId: string) =>
  constructRead(issuer, constructMutexExecOpsClaimKey(execId));

export const constructMutexExecOpsClaimTake = (execId: string) => constructTake(constructMutexExecOpsClaimKey(execId));

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

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

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