import { beforeEach, test } from 'vitest';
import { LucidContext, runAndAwaitTxBuilder } from './test-helpers';
import { EmulatorAccount, Lucid } from '@lucid-evolution/lucid';
import { Emulator } from '@lucid-evolution/lucid';
import { generateEmulatorAccount } from '@lucid-evolution/lucid';
import { addrDetails } from '../src/utils/lucid-utils';
import {
  feedInterestOracle,
  InterestOracleParams,
  startInterestOracle,
} from '../src';
import { findInterestOracle } from './queries/interest-oracle-queries';
import { benchmarkAndAwaitTx } from './utils/benchmark-utils';
import { MAINNET_PROTOCOL_PARAMETERS } from './indigo-test-helpers';

type InterestOracleTestContext = LucidContext<{
  admin: EmulatorAccount;
  user: EmulatorAccount;
}>;

beforeEach<InterestOracleTestContext>(
  async (context: InterestOracleTestContext) => {
    context.users = {
      admin: generateEmulatorAccount({}),
      user: generateEmulatorAccount({
        lovelace: BigInt(100_000_000_000_000),
      }),
    };

    context.emulator = new Emulator(
      [context.users.user],
      MAINNET_PROTOCOL_PARAMETERS,
    );

    context.lucid = await Lucid(context.emulator, 'Custom');
  },
);

test<InterestOracleTestContext>('Interest Oracle - Start', async ({
  lucid,
  users,
  emulator,
}: InterestOracleTestContext) => {
  lucid.selectWallet.fromSeed(users.user.seedPhrase);

  const [pkh, _] = await addrDetails(lucid);

  const [tx, _ac] = await startInterestOracle(
    0n,
    0n,
    0n,
    {
      biasTime: 120_000n,
      owner: pkh.hash,
    },
    lucid,
  );

  await benchmarkAndAwaitTx('Interest Oracle - Start', tx, lucid, emulator);
});

test<InterestOracleTestContext>('Interest Oracle - Update', async ({
  lucid,
  users,
  emulator,
}: InterestOracleTestContext) => {
  lucid.selectWallet.fromSeed(users.user.seedPhrase);

  const [pkh, _] = await addrDetails(lucid);
  const interestParams: InterestOracleParams = {
    biasTime: 120_000n,
    owner: pkh.hash,
  };

  const [tx, assetClass] = await startInterestOracle(
    0n,
    0n,
    0n,
    interestParams,
    lucid,
  );

  await runAndAwaitTxBuilder(lucid, tx);

  const utxo = await findInterestOracle(lucid, assetClass);

  await benchmarkAndAwaitTx(
    'Interest Oracle - Update',
    await feedInterestOracle(
      interestParams,
      500_000n,
      lucid,
      emulator.slot,
      undefined,
      utxo,
    ),
    lucid,
    emulator,
  );
});
