import { readFileSync } from 'node:fs';
import { env } from '../config/env';

/**
 * Push notifications to the mobile app, through Firebase Cloud Messaging —
 * Android directly, iOS through APNs behind it. Mirrors the email lib: every
 * push the product sends goes through `sendPush`, and the provider is env.
 *
 *   PUSH_PROVIDER=log — the default: a dry run that logs and sends nothing
 *   PUSH_PROVIDER=fcm — Firebase, with the service-account key in
 *                       FIREBASE_SERVICE_ACCOUNT (the JSON, or its base64)
 *                       or FIREBASE_SERVICE_ACCOUNT_FILE (its path)
 *
 * `data` travels with the push so the app can open the right screen when it
 * is tapped; FCM requires every value to be a string.
 */
export interface PushMessage {
  title: string;
  body: string;
  data: Record<string, string>;
  /** The Android notification channel; the app creates these. Left out, the everyday `hostelcare` one. */
  channelId?: string;
}

/** The app's louder channel, for an emergency being raised. Documented in docs/enterprise/mobile-contract.md. */
export const EMERGENCY_PUSH_CHANNEL = 'hostelcare_emergency';

export type PushMode = 'fcm' | 'log' | 'fcm-error';

export interface PushResult {
  mode: PushMode;
  /** How many devices accepted it (every device, on a dry run). */
  sent: number;
  /** Tokens the push service says are gone for good: uninstalled, or a reinstall. */
  deadTokens: string[];
}

export function isPushConfigured(): boolean {
  return env.PUSH_PROVIDER === 'fcm' && !!(env.FIREBASE_SERVICE_ACCOUNT || env.FIREBASE_SERVICE_ACCOUNT_FILE);
}

/** The service-account JSON, from the env value or the file it names. */
function serviceAccountJson(): string {
  if (env.FIREBASE_SERVICE_ACCOUNT_FILE) return readFileSync(env.FIREBASE_SERVICE_ACCOUNT_FILE, 'utf8');
  const raw = env.FIREBASE_SERVICE_ACCOUNT!.trim();
  return raw.startsWith('{') ? raw : Buffer.from(raw, 'base64').toString('utf8');
}

// The SDK is loaded on first use, so a server with push switched off never
// pays for it — and never needs credentials to start.
type Messaging = import('firebase-admin/messaging').Messaging;
let messaging: Messaging | null = null;

async function fcm(): Promise<Messaging> {
  if (messaging) return messaging;
  const json = serviceAccountJson();
  const { initializeApp, cert, getApps } = await import('firebase-admin/app');
  const { getMessaging } = await import('firebase-admin/messaging');
  const app = getApps()[0] ?? initializeApp({ credential: cert(JSON.parse(json)) });
  messaging = getMessaging(app);
  return messaging;
}

/** Errors that mean the token will never work again, so it should be dropped. */
const DEAD = new Set(['messaging/registration-token-not-registered', 'messaging/invalid-registration-token', 'messaging/invalid-argument']);

export async function sendPush(tokens: string[], message: PushMessage): Promise<PushResult> {
  if (tokens.length === 0) return { mode: isPushConfigured() ? 'fcm' : 'log', sent: 0, deadTokens: [] };
  if (!isPushConfigured()) {
    // eslint-disable-next-line no-console
    console.log(`[push:log] to ${tokens.length} device(s) — ${message.title}: ${message.body}`, message.data);
    return { mode: 'log', sent: tokens.length, deadTokens: [] };
  }
  try {
    const res = await (await fcm()).sendEachForMulticast({
      tokens,
      notification: { title: message.title, body: message.body },
      data: message.data,
      android: { priority: 'high', notification: { channelId: message.channelId ?? 'hostelcare' } },
      apns: { payload: { aps: { sound: 'default' } } },
    });
    const deadTokens = res.responses.flatMap((r, i) => (!r.success && r.error && DEAD.has(r.error.code) ? [tokens[i]] : []));
    return { mode: 'fcm', sent: res.successCount, deadTokens };
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error('[push] send failed:', err);
    return { mode: 'fcm-error', sent: 0, deadTokens: [] };
  }
}
