import { Schema } from 'effect';

import { IntegerString } from './flowSchema.js';

// The lenders a `flashloan` input can borrow from. Each name selects one
// lender adapter of the v1.3 flashloan runtime (one adapter contract per
// kind) and that lender's per-chain address.
export const providerKindNames = [
  'aave-v3',
  'balancer-v2',
  'morpho-blue',
] as const;

export type ProviderKindName = (typeof providerKindNames)[number];

// The one definition of a `flashloan` input's fields, in the wire form
// (decimal-integer strings). The materialiser's `configSchema`
// (compose-builtins), the input type and its guard all derive from it.
// - `amount`: what the leg borrows, in the token's smallest unit.
// - `maxFee`: the most the lender may charge for the leg; the runtime reverts
//   `FlashloanFeeTooHigh` above it. Defaults to `flashloanMaxFee`'s rate.
export const FlashloanConfigSchema = Schema.Struct({
  providerKind: Schema.Literal(...providerKindNames),
  amount: IntegerString,
  maxFee: Schema.optional(IntegerString),
});

// A `flashloan` input as authored: the config under the literal
// `kind: "flashloan"` that discriminates inside the `MaterialiserInput` union.
export const FlashloanMaterialiserInputSchema = Schema.Struct({
  kind: Schema.Literal('flashloan'),
  ...FlashloanConfigSchema.fields,
});

export type FlashloanMaterialiserInput =
  typeof FlashloanMaterialiserInputSchema.Type;

export const isFlashloanMaterialiserInput = Schema.is(
  FlashloanMaterialiserInputSchema,
);

// Reference fee rates, in basis points of the borrowed amount, that size a
// leg's default `maxFee`. Aave v3: `FLASHLOAN_PREMIUM_TOTAL` is 5 bps on the
// markets in the registry.
const FLASHLOAN_FEE_BPS: Readonly<Record<ProviderKindName, bigint>> = {
  'aave-v3': 5n,
  'balancer-v2': 0n,
  'morpho-blue': 0n,
};

// Local rather than imported: compose-spec may depend on no @lifi/* package.
const BPS_DENOMINATOR = 10_000n;

// The fee cap of one leg: the input's own `maxFee`, else the reference rate
// rounded up. Rounding up matters: Aave rounds its premium half-up
// (`percentMul`), so a rounded-down cap can sit one unit below the fee it
// charges and revert the flight. Amounts are wire strings or bigints, so an
// author who holds a bigint does not format it first.
export const flashloanMaxFee = ({
  providerKind,
  amount,
  maxFee,
}: {
  readonly providerKind: ProviderKindName;
  readonly amount: string | bigint;
  readonly maxFee?: string | bigint;
}): bigint =>
  maxFee !== undefined
    ? BigInt(maxFee)
    : (BigInt(amount) * FLASHLOAN_FEE_BPS[providerKind] +
        BPS_DENOMINATOR -
        1n) /
      BPS_DENOMINATOR;
