import axios from 'axios';

export async function archiveIso20022(payload: {
  messageType: string;
  direction: 'INBOUND' | 'OUTBOUND';
  raw: string;
  settlementRef: string;
}): Promise<{ messageId: string }> {
  const base = (process.env.TOKEN_AGGREGATION_URL || 'http://localhost:3000').replace(/\/$/, '');
  const key = process.env.OMNL_API_KEY || '';
  const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  if (key) headers.Authorization = `Bearer ${key}`;

  const { data } = await axios.post(
    `${base}/api/v1/omnl/iso20022/messages`,
    {
      messageType: payload.messageType,
      direction: payload.direction,
      payload: payload.raw,
      metadata: { settlementRef: payload.settlementRef },
    },
    { headers, timeout: 60000 },
  );
  return { messageId: String(data.messageId ?? data.id ?? payload.settlementRef) };
}

export async function requestTokenMint(payload: {
  lineId: string;
  amount: string;
  recipient: string;
  settlementRef: string;
  dryRun: boolean;
  symbol?: string;
  tokenAddress?: string;
}): Promise<{ txHash?: string; status: string }> {
  const base = (process.env.TOKEN_AGGREGATION_URL || 'http://localhost:3000').replace(/\/$/, '');
  const key = process.env.OMNL_API_KEY || '';
  const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  if (key) headers.Authorization = `Bearer ${key}`;

  try {
    const { data } = await axios.post(
      `${base}/api/v1/omnl/settlement/token-load`,
      payload,
      { headers, timeout: 120000 },
    );
    return {
      txHash: data.txHash,
      status: String(data.status ?? (payload.dryRun ? 'DRY_RUN' : 'SUBMITTED')),
    };
  } catch (err) {
    if (axios.isAxiosError(err) && err.response?.status === 404) {
      return {
        status: payload.dryRun ? 'DRY_RUN' : 'PENDING_CHAIN_ENDPOINT',
      };
    }
    throw err;
  }
}

export async function requestTokenTransfer(payload: {
  tokenAddress: string;
  amount: string;
  recipient: string;
  settlementRef: string;
  dryRun: boolean;
  symbol?: string;
}): Promise<{ txHash?: string; status: string }> {
  const base = (process.env.TOKEN_AGGREGATION_URL || 'http://localhost:3000').replace(/\/$/, '');
  const key = process.env.OMNL_API_KEY || '';
  const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  if (key) headers.Authorization = `Bearer ${key}`;

  try {
    const { data } = await axios.post(
      `${base}/api/v1/omnl/settlement/token-transfer`,
      payload,
      { headers, timeout: 120000 },
    );
    return {
      txHash: data.txHash,
      status: String(data.status ?? (payload.dryRun ? 'DRY_RUN' : 'SUBMITTED')),
    };
  } catch (err) {
    if (axios.isAxiosError(err) && err.response?.status === 404) {
      return {
        status: payload.dryRun ? 'DRY_RUN' : 'PENDING_CHAIN_ENDPOINT',
      };
    }
    throw err;
  }
}
