import { persistAndPushUserNotification } from '@/lib/notifications/persistUserNotification'
import type { getDb } from '@/server/db'

type AppDb = Awaited<ReturnType<typeof getDb>>

/** 申請加入家族核准後通知申請人 */
export async function notifyGroupApplyApproved(
    db: AppDb,
    {
        groupId,
        applicantUserId,
        actorUserId,
    }: {
        groupId: string
        applicantUserId: string
        actorUserId: string
    }
): Promise<void> {
    const group = await db.get<{ name: string }>(
        `SELECT name FROM groups WHERE group_id = ?`,
        [groupId]
    )
    if (!group) return

    const actorRow = await db.get<{ displayName: string }>(
        `SELECT display_name AS displayName FROM users WHERE user_id = ?`,
        [actorUserId]
    )

    const groupName = String(group.name ?? '').trim() || groupId
    const actorName = String(actorRow?.displayName ?? '').trim() || actorUserId
    const redirectUrl = `/groups/${encodeURIComponent(groupId)}`

    await persistAndPushUserNotification(db, applicantUserId, 'group_apply_approved', {
        groupName,
        actorName,
    }, redirectUrl)
}
