const DEFAULT_WEBHOOK_URL =
  process.env.TELEGRAM_WEBHOOK_URL ??
  process.env.FINANCE_BOT_WEBHOOK_URL ??
  'http://192.168.9.28:8889/webhook/transaction';
const DEFAULT_WEBHOOK_SECRET =
  process.env.TELEGRAM_WEBHOOK_SECRET ??
  process.env.FINANCE_BOT_WEBHOOK_SECRET ??
  'ktapp.cc';

interface TransactionPayload {
  [key: string]: unknown;
}

async function postToWebhook(
  payload: TransactionPayload,
  webhookURL: string,
  webhookSecret: string,
) {
  try {
    const response = await fetch(webhookURL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${webhookSecret}`,
      },
      body: JSON.stringify(payload),
    });

    if (!response.ok) {
      const text = await response.text().catch(() => '');
      console.error(
        '[telegram-webhook] Failed to notify webhook',
        response.status,
        text,
      );
    }
  } catch (error) {
    console.error('[telegram-webhook] Webhook request error', error);
  }
}

export async function notifyTransactionWebhook(
  transaction: TransactionPayload,
  options: {
    webhookURL?: string;
    webhookSecret?: string;
    action?: string;
    source?: string;
  } = {},
) {
  const url = (options.webhookURL ?? DEFAULT_WEBHOOK_URL).trim();
  const secret = (options.webhookSecret ?? DEFAULT_WEBHOOK_SECRET).trim();

  if (!url || !secret) {
    return;
  }

  const payload: TransactionPayload = {
    ...transaction,
  };

  if (options.action) {
    payload.action = options.action;
  }

  if (options.source) {
    payload.source = options.source;
  } else {
    payload.source = payload.source ?? 'finwise-backend';
  }

  await postToWebhook(payload, url, secret);
}
