import { EVM_NATIVE_SENTINEL } from './chainCapabilities.js';

export type Availability = 'now' | 'future';

export interface OutputAmount {
  readonly expected: bigint;
  readonly min?: bigint;
}

export interface NativeResource {
  readonly kind: 'native';
  readonly chainId: number;
}

export interface ERC20Resource {
  readonly kind: 'erc20';
  readonly token: string;
  readonly chainId: number;
}

export type Resource = NativeResource | ERC20Resource;

export const erc20Resource = (token: string, chainId: number): Resource => ({
  kind: 'erc20',
  token,
  chainId,
});

export const nativeResource = (chainId: number): Resource => ({
  kind: 'native',
  chainId,
});

export const isERC20Resource = (r: Resource): r is ERC20Resource =>
  r.kind === 'erc20';

export const isNativeResource = (r: Resource): r is NativeResource =>
  r.kind === 'native';

// Both switches below have no `default`: a returning function that misses a
// kind fails to compile (TS2366), which lists every branch when `Resource`
// grows. compose-spec cannot import `assertNever` from `@lifi/utils`.
export const resourcesEqual = (a: Resource, b: Resource): boolean => {
  switch (a.kind) {
    case 'native':
      return b.kind === 'native' && a.chainId === b.chainId;
    case 'erc20':
      return (
        b.kind === 'erc20' &&
        a.chainId === b.chainId &&
        a.token.toLowerCase() === b.token.toLowerCase()
      );
  }
};

// Each arm receives the narrowed member, so a helper that only applies to one
// kind takes that member (`ERC20Resource`) rather than its spread fields.
export const foldResource = <R>(
  r: Resource,
  cases: {
    readonly native: (r: NativeResource) => R;
    readonly erc20: (r: ERC20Resource) => R;
  },
): R => {
  switch (r.kind) {
    case 'native':
      return cases.native(r);
    case 'erc20':
      return cases.erc20(r);
  }
};

// Canonical address representation of a resource for consumers whose wire
// contract uses the EVM-native sentinel rather than the Resource union.
export const resourceToken = (r: Resource): string =>
  foldResource(r, {
    native: () => EVM_NATIVE_SENTINEL,
    erc20: ({ token }) => token,
  });

export const resourceKey = (r: Resource): string =>
  foldResource(r, {
    native: ({ chainId }) => `native:${chainId}`,
    erc20: ({ token, chainId }) => `erc20:${token.toLowerCase()}:${chainId}`,
  });

// A resource as an error message names it.
export const describeResource = (r: Resource): string =>
  foldResource(r, {
    native: ({ chainId }) => `native coin on chain ${chainId}`,
    erc20: ({ token, chainId }) => `${token} on chain ${chainId}`,
  });

export const erc20Token = (r: Resource): string => {
  if (r.kind !== 'erc20')
    throw new Error(`Expected erc20 resource, got ${r.kind}`);
  return r.token;
};
