/** 儀表板「直播屬性」；存於 room_streams.attribute（JSON） */
export type RoomStreamAttribute = {
    hideBroadcast?: boolean
    preventExploration?: boolean
    passwordProtected?: boolean
}

const ATTRIBUTE_KEYS: (keyof RoomStreamAttribute)[] = [
    'hideBroadcast',
    'preventExploration',
    'passwordProtected',
]

function normalizeAttributeObject(raw: Record<string, unknown>): RoomStreamAttribute | null {
    const out: RoomStreamAttribute = {}
    let hasAny = false
    for (const key of ATTRIBUTE_KEYS) {
        if (!(key in raw)) continue
        const v = raw[key]
        if (typeof v !== 'boolean') continue
        out[key] = v
        hasAny = true
    }
    return hasAny ? out : null
}

export function parseRoomStreamAttribute(raw: unknown): RoomStreamAttribute | null {
    if (raw == null || raw === '') return null
    if (typeof raw === 'object' && raw !== null && !Array.isArray(raw)) {
        return normalizeAttributeObject(raw as Record<string, unknown>)
    }
    const str = String(raw).trim()
    if (!str) return null
    try {
        const parsed = JSON.parse(str) as unknown
        if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
            return normalizeAttributeObject(parsed as Record<string, unknown>)
        }
    } catch {
        return null
    }
    return null
}

export function serializeRoomStreamAttribute(
    attribute: RoomStreamAttribute | null | undefined
): string {
    const parsed = parseRoomStreamAttribute(attribute)
    if (!parsed) return ''
    return JSON.stringify(parsed)
}

export function defaultRoomStreamAttribute(): RoomStreamAttribute {
    return {
        hideBroadcast: false,
        preventExploration: false,
        passwordProtected: false,
    }
}

export function resolveRoomStreamAttribute(raw: unknown): RoomStreamAttribute {
    const parsed = parseRoomStreamAttribute(raw)
    const defaults = defaultRoomStreamAttribute()
    return {
        hideBroadcast: parsed?.hideBroadcast ?? defaults.hideBroadcast,
        preventExploration: parsed?.preventExploration ?? defaults.preventExploration,
        passwordProtected: parsed?.passwordProtected ?? defaults.passwordProtected,
    }
}
