import 'server-only';
import { db } from './db';
import { notifyInbox } from './bus';
import { sendEmail, emailLayout, APP_URL } from './email';

export type NotifyInput = {
  type: string;
  title: string;
  body?: string;
  /** App path the notification links to, e.g. /compte?tab=messages */
  link?: string;
  /** Also send an email. */
  email?: boolean;
  emailHtml?: string;
  emailCta?: { label: string; url: string };
  /** notif_prefs key that gates the email (e.g. 'msg', 'resa'). */
  prefKey?: string;
};

/** Create an in-app notification (+ optional email) and push it in real-time. */
export function notify(userId: number, input: NotifyInput): void {
  if (!userId) return;
  db.prepare(
    'INSERT INTO notifications (user_id, type, title, body, link, read, created_at) VALUES (?, ?, ?, ?, ?, 0, ?)'
  ).run(userId, input.type, input.title, input.body || '', input.link || '', Date.now());
  notifyInbox(userId); // real-time bell refresh via SSE

  if (input.email) {
    const u = db.prepare('SELECT email, notif_prefs FROM users WHERE id = ?').get(userId) as
      | { email: string; notif_prefs: string }
      | undefined;
    if (u && u.email && !u.email.endsWith('@darsouk.local')) {
      let prefs: Record<string, boolean> = {};
      try {
        prefs = u.notif_prefs ? JSON.parse(u.notif_prefs) : {};
      } catch {
        prefs = {};
      }
      const allowed = input.prefKey ? prefs[input.prefKey] !== false : true;
      if (allowed) {
        const html = input.emailHtml || emailLayout(input.title, `<p>${input.body || ''}</p>`, input.emailCta);
        void sendEmail({ to: u.email, subject: input.title, html, text: input.body });
      }
    }
  }
}

export const appUrl = (path: string) => `${APP_URL}${path}`;
