import { constructClaim } from '@coinweb/contract-kit';
import { cwait, lock, readOp, storeOp, TypedClaim } from 'cwait';

import { createWordKey, WordClaimBody } from '../offchain';

import { extraLogic2 } from './extraLogic2';

export const extraLogic = cwait(async (id: string, i: number) => {
  console.log('extraLogic START ++ ', i);

  console.log('extraLogic lock + ', i);
  const unlock = await lock(createWordKey(id));

  console.log('extraLogic readOp + ', i);
  const result = await readOp<TypedClaim<WordClaimBody>>(createWordKey(id));

  console.log('extraLogic storeOp + ', i);
  await storeOp(
    constructClaim(
      createWordKey(id),
      { word: result?.body.word.split('').reverse().join('') + '_extraLogic + ' + i },
      '0x0'
    )
  );

  console.log('extraLogic unlock + ', i);
  await unlock();

  console.log('extraLogic return extraLogic2 + ', i);
  return extraLogic2(id, i);
});
