import type { ComposeCompileRequest, Flow } from '@lifi/compose-spec';

import {
  type ComposeCompileResult,
  createComposeSdk,
  guards,
  isComposeError,
  materialisers,
  resources,
} from '../index.js';
import type { Address } from '../types.js';

import { API_KEY, BASE_URL } from './config.js';
import { payInvoice, type UsdcInvoice } from './continuationExactInvoice.js';

const BASE = 8453;
const USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
const WETH = '0x4200000000000000000000000000000000000006';

export interface PayInvoiceWithMinAmountInput {
  readonly owner: Address;
  readonly invoice: UsdcInvoice;
  // WETH base units (18 decimals) swapped to USDC. The swap's guaranteed
  // output (its quote less `slippage`) must cover the invoice total, or the
  // compile fails with the shortfall.
  readonly wethAmount: `${bigint}`;
}

/**
 * Pay a Request Network USDC invoice on Base from WETH in one transaction:
 * swap WETH to USDC, split the invoice total off the swap output, pay it, and
 * sweep the surplus back to the sender.
 *
 * Demonstrates:
 * - `guards.minAmount` on `core.splitAt`'s `head`. The split caps `head` at
 *   the invoice total, but it passes on only what reaches it. The guard, with
 *   the same amount, turns that cap into a floor: `head` carries the whole
 *   total on every run, or the flow does not compile.
 * - The compile-time check. The backend proves `head`'s minimum from the op
 *   floors in front of it: here the swap's guaranteed output, never its
 *   expected one. A minimum below the total fails the compile with
 *   `validation_error` and a `shortfall` (see `compilePayInvoice`) under every
 *   `simulationPolicy`, instead of returning a transaction that reverts in
 *   the fee proxy's `transferFrom`.
 * - The on-chain check. The guard also emits `head >= total` into the
 *   transaction, and the response reports the total as `head`'s minimum.
 *
 * A guard applies to resource outputs only. A port that provides its own
 * minimum (`lifi.swap`'s `amountOut`) or delivers in the future rejects it.
 */
export const buildPayInvoiceWithMinAmount = ({
  owner,
  invoice,
  wethAmount,
}: PayInvoiceWithMinAmountInput): {
  flow: Flow;
  request: ComposeCompileRequest;
} => {
  const sdk = createComposeSdk({ baseUrl: BASE_URL, apiKey: API_KEY });
  const total = `${invoice.amount + invoice.fee}` as const;

  const builder = sdk.flow(BASE, {
    name: 'swap-and-pay-invoice-min-amount',
    inputs: { weth: resources.erc20(WETH, BASE) },
  });
  const swap = builder.lifi.swap('swap', {
    bind: { amountIn: builder.inputs.weth },
    config: { resourceOut: resources.erc20(USDC, BASE), slippage: 0.005 },
  });
  // `config.amount` caps `head` at the total; the guard requires it there.
  const { head } = builder.core.splitAt('invoice', {
    bind: { source: swap.amountOut },
    config: { amount: total },
    guards: [guards.minAmount({ port: 'head', amount: total })],
  });
  payInvoice(builder, head, invoice);

  const flow = builder.build();

  const request = sdk.request(flow, {
    signer: owner,
    inputs: {
      weth: materialisers.directDeposit({ amount: wethAmount }),
    },
    // `tail`, the USDC above the total, returns to the sender.
    sweepTo: builder.context.sender,
    // The invoice payment leaves the flow, so the price-impact check would
    // count it as lost value. `0` disables the check.
    maxPriceImpactBps: 0,
  });

  return { flow, request };
};

/**
 * Compile the flow above, and turn a `minAmount` shortfall into an
 * actionable message.
 *
 * This function is illustrative: it needs a live backend. The shortfall
 * error carries `path` (the guarded node, `invoice`), `port` (`head`) and
 * `shortfall`, whose amounts are decimal strings in the units of the guarded
 * port's token (USDC base units here):
 * - `required` is the guard's `amount`, the invoice total.
 * - `available` is the minimum the flow guarantees at `head`: the swap's
 *   guaranteed output when that is below the total.
 */
export const compilePayInvoice = async (
  input: PayInvoiceWithMinAmountInput,
): Promise<ComposeCompileResult> => {
  const sdk = createComposeSdk({ baseUrl: BASE_URL, apiKey: API_KEY });
  const { request } = buildPayInvoiceWithMinAmount(input);
  try {
    return await sdk.client.compile(request);
  } catch (e) {
    if (
      !isComposeError(e) ||
      e.kind !== 'validation_error' ||
      e.path !== 'invoice' ||
      e.shortfall === undefined
    ) {
      throw e;
    }
    const missing =
      BigInt(e.shortfall.required) - BigInt(e.shortfall.available);
    throw new Error(
      `The swap guarantees ${e.shortfall.available} USDC base units, ${missing} short of the invoice total ${e.shortfall.required}: deposit more WETH or lower the slippage`,
      { cause: e },
    );
  }
};
