import { constructContinueTx, Context, extractContractArgs, extractRead } from '@coinweb/contract-kit';
import { getContractArguments } from 'lib/onchain';
import { TypedClaim } from 'lib/shared';

import { constructMutexAccessClaimStore } from '../claims';
import { MutexAccessStatus, MutexGetAccessArgs, MutexLockState } from '../types';
import { isMatchLockKeys } from '../utils';

export const mutexGetAccess = (context: Context) => {
  const [claimKey, processId, uniqueId] = getContractArguments<MutexGetAccessArgs>(context);

  const lockQueue = extractRead(extractContractArgs(context.tx)[0])?.map(
    ({ content }) => content as TypedClaim<MutexLockState>
  );

  if (!lockQueue) {
    throw new Error('No lock queue found');
  }

  const isLockedByOtherProcess = lockQueue.some(
    ({ body }) => body.locked && body.processId !== processId && body.keys.some((key) => isMatchLockKeys(key, claimKey))
  );

  return [
    constructContinueTx(context, [
      constructMutexAccessClaimStore(
        uniqueId,
        isLockedByOtherProcess ? MutexAccessStatus.DENIED : MutexAccessStatus.GRANTED
      ),
    ]),
  ];
};
