import { openStore } from "@/lib/data/store";

/**
 * Sends a push notification through OneSignal, when configured.
 *
 * Silent about failures — a push not arriving must never interfere with the
 * on-site notification that triggered it.
 */
export async function sendPush(opts: {
  userId: string;
  heading: string;
  text: string;
  url?: string;
}): Promise<{ sent: boolean; reason?: string }> {
  const store = await openStore();
  const s = await store.settings();

  if (s.pushEnabled !== true) return { sent: false, reason: "Push is turned off" };

  const appId = String(s.oneSignalAppId ?? "").trim();
  const apiKey = String(s.oneSignalApiKey ?? "").trim();
  if (!appId || !apiKey) {
    return { sent: false, reason: "OneSignal isn't configured" };
  }

  try {
    const res = await fetch("https://onesignal.com/api/v1/notifications", {
      method: "POST",
      headers: {
        Authorization: `Basic ${apiKey}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        app_id: appId,
        // People are tagged with their account id when they subscribe.
        filters: [{ field: "tag", key: "userId", relation: "=", value: opts.userId }],
        headings: { en: opts.heading },
        contents: { en: opts.text },
        ...(opts.url ? { url: opts.url } : {}),
      }),
    });

    return res.ok
      ? { sent: true }
      : { sent: false, reason: "OneSignal refused the notification" };
  } catch {
    return { sent: false, reason: "Couldn't reach OneSignal" };
  }
}


/**
 * Sends a notification through whichever messaging apps are switched on.
 *
 * Each is independent: one being misconfigured shouldn't stop the others,
 * so a failure is swallowed per app rather than for the batch.
 */
export async function notifyByApp(
  settings: Record<string, unknown>,
  to: { telegramChatId?: string; whatsappNumber?: string },
  text: string
) {
  const jobs: Promise<unknown>[] = [];

  if (settings.telegramEnabled === true && to.telegramChatId) {
    const token = String(settings.telegramBotToken ?? "").trim();
    if (token) {
      jobs.push(
        fetch(`https://api.telegram.org/bot${token}/sendMessage`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ chat_id: to.telegramChatId, text }),
        }).catch(() => null)
      );
    }
  }

  if (settings.whatsappEnabled === true && to.whatsappNumber) {
    const token = String(settings.whatsappToken ?? "").trim();
    const phoneId = String(settings.whatsappPhoneId ?? "").trim();

    if (token && phoneId) {
      jobs.push(
        fetch(`https://graph.facebook.com/v18.0/${phoneId}/messages`, {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            messaging_product: "whatsapp",
            to: to.whatsappNumber,
            type: "text",
            text: { body: text },
          }),
        }).catch(() => null)
      );
    }
  }

  await Promise.all(jobs);
}

/** Posts to a Discord channel — for admin alerts rather than members. */
export async function notifyDiscord(
  settings: Record<string, unknown>,
  text: string
) {
  if (settings.discordEnabled !== true) return;

  const hook = String(settings.discordWebhook ?? "").trim();
  if (!hook) return;

  await fetch(hook, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ content: text.slice(0, 1900) }),
  }).catch(() => null);
}
