import { OnTransactionHandler } from '@metamask/snaps-types';
import {
  panel,
  text,
  heading,
  Text,
  copyable,
  Copyable,
} from '@metamask/snaps-ui';
import { doCAMLVerification } from './caml-client';

/**
 * Handle transaction confirmation requests
 *
 * @param obj.transaction - Transaction object. A reference to the tx an user is about to perform
 * @returns response with insights content text
 */
export const onTransaction: OnTransactionHandler = async ({ transaction }) => {
  const txToAddr = transaction.to as string;
  const camlResults = await doCAMLVerification(txToAddr);
  const outputBody: (Text | Copyable)[] = [];
  let title: string;
  if (camlResults.error) {
    title = 'Error';
    outputBody.push(text('😕 Oops... something went wrong.'));
    outputBody.push(
      text(
        `Unable to perform CAML verification: ${camlResults.error}. Please try again`,
      ),
    );
  } else if (camlResults.foundMatch) {
    title = 'Alert';
    outputBody.push(
      text(
        `💡 Found **${camlResults.totalMatches}** match${
          camlResults.totalMatches > 1 ? 'es' : ''
        } on AML list for address **${txToAddr}**.`,
      ),
    );

    outputBody.push(
      text(
        'The address may be associated to illicit transactions. Please verify before continuing your transaction.',
      ),
    );

    outputBody.push(
      text('Copy and open below url on your browser to see full results.'),
    );
    outputBody.push(copyable(camlResults.resultsUrl));
  } else {
    title = 'Notice';
    outputBody.push(
      text(`✅ No AML matches found for address **${txToAddr}**.`),
    );

    outputBody.push(
      text(
        '🚧 You can continue your transaction. This does not guarantee that it is 100% safe. Proceed with care.',
      ),
    );
  }

  return {
    content: panel([heading(`CAML ${title}`), ...outputBody]),
  };
};
