import { randomBytes } from 'crypto'
import type { getDb } from '@/server/db'
import type { GroupNotificationParams, UserNotificationWsPayload } from '@/lib/notifications/userNotificationTypes'
import { pushUserNotificationWs } from '@/lib/notifications/pushUserNotificationWs'
import { getUserNotificationPrefs } from '@/server/notifications/getUserNotificationPrefs'

type AppDb = Awaited<ReturnType<typeof getDb>>

function newNotificationId(): string {
    return `ntf_${Date.now()}_${randomBytes(4).toString('hex')}`
}

/**
 * 依使用者通知設定寫入紀錄並／或 WS 推播。
 * - record_enabled：寫入 user_notifications
 * - push_enabled 或 record：經 WS 即時通知（客戶端可再觸發桌面推播）
 */
export async function persistAndPushUserNotification(
    db: AppDb,
    userId: string,
    type: string,
    params: GroupNotificationParams,
    redirectUrl: string
): Promise<UserNotificationWsPayload | null> {
    const prefs = await getUserNotificationPrefs(db, userId, type)
    if (!prefs.record && !prefs.push) {
        return null
    }

    const content = JSON.stringify(params)
    const createdAt = Math.floor(Date.now() / 1000)
    let id = newNotificationId()

    if (prefs.record) {
        await db.run(
            `INSERT INTO user_notifications (notification_id, user_id, type, title, content, redirect_url, is_read, created_at)
             VALUES (?, ?, ?, ?, ?, ?, 0, ?)`,
            [id, userId, type, '', content, redirectUrl, createdAt]
        )
    } else {
        id = newNotificationId()
    }

    const payload: UserNotificationWsPayload = {
        id,
        type,
        title: '',
        content,
        url: redirectUrl,
        isRead: false,
        createdAt,
        params,
        pushEnabled: prefs.push,
        desktopEnabled: prefs.desktopEnabled,
    }

    await pushUserNotificationWs(userId, payload)
    return payload
}
