import { NextResponse } from 'next/server';
import { loadSettings } from '@/lib/settings';

export async function POST() {
  const settings = loadSettings();
  const { telegramBotToken, telegramChatId } = settings;

  if (!telegramBotToken || !telegramChatId) {
    return NextResponse.json({ ok: false, error: 'Telegram bot token or chat ID not configured' });
  }

  // telegramChatId may be a comma-separated whitelist. The test message
  // goes to the FIRST id so a misconfigured later id doesn't fail the test.
  const firstChatId = telegramChatId.split(',').map((s) => s.trim()).filter(Boolean)[0];
  if (!firstChatId) {
    return NextResponse.json({ ok: false, error: 'telegramChatId is empty / malformed' });
  }

  try {
    const url = `https://api.telegram.org/bot${telegramBotToken}/sendMessage`;
    // Plain text — no parse_mode — so an em-dash / asterisk / underscore
    // can never trip Telegram's Markdown parser ("can't parse entities").
    const res = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        chat_id: firstChatId,
        text: '✅ Forge — Test notification! Telegram notifications are working.',
      }),
    });

    const body = await res.text();
    if (!res.ok) {
      // Surface Telegram's "description" — covers the common cases like
      // "chat not found", "Unauthorized" (token revoked), "bot was blocked".
      try {
        const j = JSON.parse(body);
        return NextResponse.json({ ok: false, error: `${res.status} ${j.description || body}` });
      } catch {
        return NextResponse.json({ ok: false, error: `${res.status} ${body}` });
      }
    }
    return NextResponse.json({ ok: true });
  } catch (err: any) {
    // 'fetch failed' from Node is opaque — almost always corp SSL inspection
    // (Zscaler / corporate firewall) or proxy / DNS / network. Surface
    // concrete remediation in the alert so the user doesn't have to guess.
    const msg = String(err?.message || err);
    if (/fetch failed|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|UNABLE_TO_VERIFY|self.signed/i.test(msg)) {
      const cause = err?.cause?.code || err?.cause?.message || '';
      return NextResponse.json({
        ok: false,
        error: [
          `${msg}${cause ? ' (cause: ' + cause + ')' : ''}`,
          '',
          'Forge could not reach api.telegram.org. Common causes:',
          '  • Corporate TLS inspection — set NODE_EXTRA_CA_CERTS=/path/to/corp-ca.pem then `forge server restart`',
          '  • HTTP proxy required — set HTTPS_PROXY=http://proxy.corp:port then restart',
          '  • Network / DNS — curl -v https://api.telegram.org/bot<TOKEN>/getMe',
        ].join('\n'),
      });
    }
    return NextResponse.json({ ok: false, error: msg });
  }
}
