import { Transaction } from '@mysten/sui/transactions';
import { createSuiClient } from './client.js';
import { SUI_PACKAGE_ID } from '../../constants.js';

export async function getSuiCancelCrossChainOrder(orderId: string): Promise<Transaction> {
  const client = createSuiClient();
  const order = await client.getObject({
    id: orderId,
    options: {
      showContent: true,
    },
  });

  if (!order.data) {
    throw new Error(`Order ${orderId} not found`);
  }

  if (!order.data.content || order.data.content.dataType !== 'moveObject') {
    throw new Error(`Order ${orderId} is not a move object`);
  }

  if (!order?.data?.content?.type) {
    throw new Error(`Order ${orderId} has no type`);
  }

  const matched = order.data.content.type.match(/<([^>]+)>/)!;

  if (!matched[1]) {
    throw new Error(`Order ${orderId} has no type arguments`);
  }

  const typeArguments = matched[1].split(', ');
  const tx = new Transaction();

  tx.moveCall({
    package: SUI_PACKAGE_ID,
    module: 'source_chain_guard',
    function: 'cancel_order',
    arguments: [tx.object(orderId), tx.object.clock()],
    typeArguments,
  });

  return tx;
}
