// Server-only helpers for the dashboard alerts inbox.
import { and, eq, gt } from 'drizzle-orm'
import { db } from '../../db/index.js'
import { notifications } from '../../db/schema.js'

export type NotificationType = 'sign_in' | 'purchase' | 'adjustment' | 'security'

// Alerts are a convenience, so a failure here never breaks the action that
// triggered it (a payment or sign-in).
export async function notify(userId: string, alert: { type: NotificationType; title: string; body: string }) {
  try {
    await db.insert(notifications).values({ userId, ...alert })
  } catch (error) {
    console.error('Could not save alert', alert.type, error)
  }
}

// Turns a User-Agent header into something like "Chrome on Android".
export function describeDevice(userAgent: string | undefined | null) {
  if (!userAgent) return 'an unknown device'
  const browser = /Edg\//.test(userAgent)
    ? 'Edge'
    : /OPR\/|Opera/.test(userAgent)
      ? 'Opera'
      : /SamsungBrowser/.test(userAgent)
        ? 'Samsung Internet'
        : /Firefox\//.test(userAgent)
          ? 'Firefox'
          : /Chrome\//.test(userAgent)
            ? 'Chrome'
            : /Safari\//.test(userAgent)
              ? 'Safari'
              : 'a browser'
  const os = /Android/.test(userAgent)
    ? 'Android'
    : /iPhone|iPad|iPod/.test(userAgent)
      ? 'iOS'
      : /Windows/.test(userAgent)
        ? 'Windows'
        : /Mac OS X/.test(userAgent)
          ? 'macOS'
          : /Linux/.test(userAgent)
            ? 'Linux'
            : null
  return os ? `${browser} on ${os}` : browser
}

// Records a sign-in alert, skipping repeats within a minute (e.g. a sign-in
// reported by two tabs at once). Returns whether a new alert was recorded.
export async function notifySignIn(userId: string, userAgent: string | undefined | null) {
  const [recent] = await db
    .select({ id: notifications.id })
    .from(notifications)
    .where(
      and(
        eq(notifications.userId, userId),
        eq(notifications.type, 'sign_in'),
        gt(notifications.createdAt, new Date(Date.now() - 60_000)),
      ),
    )
    .limit(1)
  if (recent) return false
  await notify(userId, {
    type: 'sign_in',
    title: 'New sign-in to your account',
    body: `You signed in from ${describeDevice(userAgent)}. If this wasn’t you, reset your password straight away.`,
  })
  return true
}
