import type { TFunction } from 'i18next'
import type { GroupNotificationParams } from '@/lib/notifications/userNotificationTypes'

function parseParams(content: string, fallback?: GroupNotificationParams): GroupNotificationParams {
    if (fallback) return fallback
    try {
        const parsed = JSON.parse(content || '{}') as GroupNotificationParams
        return {
            groupName: String(parsed.groupName ?? ''),
            actorName: String(parsed.actorName ?? ''),
            targetName: parsed.targetName != null ? String(parsed.targetName) : undefined,
        }
    } catch {
        return { groupName: '', actorName: '' }
    }
}

const GROUP_NOTICE_I18N_KEYS: Record<string, { title: string; content: string }> = {
    group_transfer_leader_target: {
        title: 'notifications.group.transferLeaderTarget.title',
        content: 'notifications.group.transferLeaderTarget.content',
    },
    group_transfer_leader_broadcast: {
        title: 'notifications.group.transferLeaderBroadcast.title',
        content: 'notifications.group.transferLeaderBroadcast.content',
    },
    group_promote_deputy: {
        title: 'notifications.group.promoteDeputy.title',
        content: 'notifications.group.promoteDeputy.content',
    },
    group_demote_member: {
        title: 'notifications.group.demoteMember.title',
        content: 'notifications.group.demoteMember.content',
    },
    group_kick: {
        title: 'notifications.group.kick.title',
        content: 'notifications.group.kick.content',
    },
    group_apply_approved: {
        title: 'notifications.group.applyApproved.title',
        content: 'notifications.group.applyApproved.content',
    },
}

export function resolveGroupNotificationText(
    t: TFunction,
    type: string,
    content: string,
    params?: GroupNotificationParams
): { title: string; content: string } | null {
    const keys = GROUP_NOTICE_I18N_KEYS[type]
    if (!keys) return null
    const p = parseParams(content, params)
    return {
        title: t(keys.title, p),
        content: t(keys.content, p),
    }
}
