const logger = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/logger.js`)
const { createAppError } = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/appError.js`)
const wechatService = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/services/wechatService.js`)
const documentService = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/services/documentService.js`)
const dictionaryService = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/services/dictionaryService.js`)
const env = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/config/env.js`)

const GUEST_USER_TYPE = '游客'
const REGISTERED_USER_TYPE = '注册用户'
const WECHAT_ID_TYPE = 'WeChat'
const MANAGE_PLATFORM_ID_TYPE = 'ManagePlatform'
const USER_LEVEL_DICT_NAME = '数据-会员等级'
const mutationLocks = {}

function buildUserId() {
    const now = new Date()
    const yyyy = String(now.getFullYear())
    const mm = String(now.getMonth() + 1)
    const dd = String(now.getDate())
    const date = yyyy + (mm.length === 1 ? '0' + mm : mm) + (dd.length === 1 ? '0' + dd : dd)
    const suffix = String(Math.floor(Math.random() * 9000) + 1000)
    return 'U' + date + suffix
}

function buildUserConversId() {
    return 'UC-' + new Date().getTime() + '-' + $security.randomString(6)
}

function buildGuid() {
    return $security.randomString(8) + '-' + $security.randomString(4) + '-' + $security.randomString(4) + '-' + $security.randomString(4) + '-' + $security.randomString(12)
}

function maskPhone(phone) {
    const value = phone || ''
    if (!value || value.length < 7) return ''
    return value.slice(0, 3) + '****' + value.slice(-4)
}

function isInfoComplete(record) {
    return !!(record.getString('users_name') && record.getString('users_phone') && record.getString('users_picture'))
}

function isAllProfileFieldsEmpty(record) {
    return !record.getString('users_name') && !record.getString('users_phone') && !record.getString('users_picture')
}

function normalizeText(value) {
    return String(value || '').replace(/^\s+|\s+$/g, '')
}

function normalizeOptionalNumber(value, fieldName) {
    const raw = normalizeText(value)
    if (!raw) {
        return null
    }

    const num = Number(raw)
    if (!Number.isFinite(num)) {
        throw createAppError(400, fieldName + ' 必须为数字')
    }

    return num
}

function getUserLevelItems() {
    try {
        return dictionaryService.getDictionaryItemsByName(USER_LEVEL_DICT_NAME)
    } catch (_error) {
        return []
    }
}

function getUserLevelOptions() {
    return getUserLevelItems().map(function (item) {
        return {
            value: String(item.enum || ''),
            label: String(item.description || ''),
            sort: Number(item.sortOrder || 0),
        }
    })
}

function resolveUserLevelName(usersLevel) {
    const level = normalizeText(usersLevel)
    if (!level) {
        return ''
    }

    const items = getUserLevelItems()
    for (let i = 0; i < items.length; i += 1) {
        if (normalizeText(items[i].enum) === level) {
            return String(items[i].description || '')
        }
    }

    return ''
}

function ensureValidUserLevel(usersLevel) {
    const level = normalizeText(usersLevel)
    if (!level) {
        return ''
    }

    const items = getUserLevelItems()
    for (let i = 0; i < items.length; i += 1) {
        if (normalizeText(items[i].enum) === level) {
            return level
        }
    }

    throw createAppError(400, 'users_level 不在“数据-会员等级”字典中')
}

function withUserLock(lockKey, handler) {
    if (mutationLocks[lockKey]) {
        throw createAppError(429, '请求过于频繁，请稍后重试')
    }

    mutationLocks[lockKey] = true

    try {
        return handler()
    } finally {
        delete mutationLocks[lockKey]
    }
}

function findUserByOpenid(usersWxOpenid) {
    const records = $app.findRecordsByFilter('tbl_auth_users', 'openid = {:openid}', '', 1, 0, {
        openid: usersWxOpenid,
    })
    return records.length ? records[0] : null
}

function findUserByPhone(usersPhone) {
    const records = $app.findRecordsByFilter('tbl_auth_users', 'users_phone = {:phone}', '', 1, 0, {
        phone: usersPhone,
    })
    return records.length ? records[0] : null
}

function findUserByEmail(email) {
    const records = $app.findRecordsByFilter('tbl_auth_users', 'email = {:email}', '', 1, 0, {
        email: email,
    })
    return records.length ? records[0] : null
}

function isEmail(value) {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(value || ''))
}

function parseHttpJsonResponse(response) {
    if (!response) {
        throw createAppError(500, 'PocketBase 认证响应为空')
    }

    if (response.json && typeof response.json === 'object') {
        return response.json
    }

    if (typeof response.body === 'string' && response.body) {
        return JSON.parse(response.body)
    }

    if (response.body && typeof response.body === 'object') {
        return response.body
    }

    if (typeof response.data === 'string' && response.data) {
        return JSON.parse(response.data)
    }

    if (response.data && typeof response.data === 'object') {
        return response.data
    }

    throw createAppError(500, 'PocketBase 认证响应体为空', {
        statusCode: response.statusCode || 0,
        responseKeys: Object.keys(response || {}),
    })
}

function decodeHttpBodyText(body) {
    if (typeof body === 'string') {
        return body
    }

    if (Array.isArray(body)) {
        return body.map(function (code) {
            return String.fromCharCode(Number(code) || 0)
        }).join('')
    }

    if (body && typeof body.length === 'number' && typeof body !== 'function') {
        try {
            let text = ''
            for (let i = 0; i < body.length; i += 1) {
                text += String.fromCharCode(Number(body[i]) || 0)
            }
            return text
        } catch (_err) {
            return String(body || '')
        }
    }

    return String(body || '')
}

function getCompanyByCompanyId(companyId) {
    if (!companyId) return null
    const records = $app.findRecordsByFilter('tbl_company', 'company_id = {:companyId}', '', 1, 0, {
        companyId: companyId,
    })
    return records.length ? records[0] : null
}

function getCompanyByOwnerOpenid(openid) {
    if (!openid) return null
    const records = $app.findRecordsByFilter('tbl_company', 'company_owner_openid = {:openid}', '', 1, 0, {
        openid: openid,
    })
    return records.length ? records[0] : null
}

function exportCompany(companyRecord) {
    if (!companyRecord) return null
    return {
        pb_id: companyRecord.id,
        company_id: companyRecord.getString('company_id'),
        company_name: companyRecord.getString('company_name'),
        company_type: companyRecord.getString('company_type'),
        company_entity: companyRecord.getString('company_entity'),
        company_usci: companyRecord.getString('company_usci'),
        company_nationality: companyRecord.getString('company_nationality'),
        company_nationality_code: companyRecord.getString('company_nationality_code'),
        company_province: companyRecord.getString('company_province'),
        company_province_code: companyRecord.getString('company_province_code'),
        company_city: companyRecord.getString('company_city'),
        company_city_code: companyRecord.getString('company_city_code'),
        company_district: companyRecord.getString('company_district'),
        company_district_code: companyRecord.getString('company_district_code'),
        company_postalcode: companyRecord.getString('company_postalcode'),
        company_add: companyRecord.getString('company_add'),
        company_status: companyRecord.getString('company_status'),
        company_level: companyRecord.getString('company_level'),
        company_owner_openid: companyRecord.getString('company_owner_openid'),
        company_remark: companyRecord.getString('company_remark'),
        created: String(companyRecord.created || ''),
        updated: String(companyRecord.updated || ''),
    }
}

function resolveUserAttachment(attachmentId) {
    const value = String(attachmentId || '')
    if (!value) {
        return {
            id: '',
            url: '',
            attachment: null,
        }
    }

    try {
        const attachment = documentService.getAttachmentDetail(value)
        return {
            id: value,
            url: attachment ? attachment.attachments_url : '',
            attachment: attachment,
        }
    } catch (_error) {
        return {
            id: value,
            url: '',
            attachment: null,
        }
    }
}

function ensureAttachmentIdExists(attachmentId, fieldName) {
    const value = String(attachmentId || '')
    if (!value) return ''

    try {
        documentService.getAttachmentDetail(value)
    } catch (_error) {
        throw createAppError(400, fieldName + ' 对应的附件不存在：' + value)
    }

    return value
}

function applyUserAttachmentFields(record, payload) {
    if (!payload) return

    if (typeof payload.users_picture !== 'undefined' && payload.users_picture) {
        record.set('users_picture', ensureAttachmentIdExists(payload.users_picture, 'users_picture'))
    }
    if (typeof payload.users_id_pic_a !== 'undefined') {
        if (payload.users_id_pic_a) {
            record.set('users_id_pic_a', ensureAttachmentIdExists(payload.users_id_pic_a, 'users_id_pic_a'))
        }
    }
    if (typeof payload.users_id_pic_b !== 'undefined') {
        if (payload.users_id_pic_b) {
            record.set('users_id_pic_b', ensureAttachmentIdExists(payload.users_id_pic_b, 'users_id_pic_b'))
        }
    }
    if (typeof payload.users_title_picture !== 'undefined') {
        if (payload.users_title_picture) {
            record.set('users_title_picture', ensureAttachmentIdExists(payload.users_title_picture, 'users_title_picture'))
        }
    }
}

function enrichUser(userRecord) {
    const openid = userRecord.getString('openid')
    let companyId = userRecord.getString('company_id')
    let companyRecord = getCompanyByCompanyId(companyId)

    if (!companyRecord && openid) {
        companyRecord = getCompanyByOwnerOpenid(openid)
        if (companyRecord) {
            companyId = companyRecord.getString('company_id')
        }
    }

    const userPicture = resolveUserAttachment(userRecord.getString('users_picture'))
    const userIdPicA = resolveUserAttachment(userRecord.getString('users_id_pic_a'))
    const userIdPicB = resolveUserAttachment(userRecord.getString('users_id_pic_b'))
    const userTitlePicture = resolveUserAttachment(userRecord.getString('users_title_picture'))

    return {
        pb_id: userRecord.id,
        users_convers_id: userRecord.getString('users_convers_id'),
        users_id: userRecord.getString('users_id'),
        users_idtype: userRecord.getString('users_idtype'),
        users_id_number: userRecord.getString('users_id_number'),
        users_type: userRecord.getString('users_type') || GUEST_USER_TYPE,
        users_name: userRecord.getString('users_name'),
        users_status: userRecord.get('users_status'),
        users_rank_level: userRecord.get('users_rank_level'),
        users_auth_type: userRecord.get('users_auth_type'),
        users_phone: userRecord.getString('users_phone'),
        users_phone_masked: maskPhone(userRecord.getString('users_phone')),
        users_level: userRecord.getString('users_level'),
        users_level_name: resolveUserLevelName(userRecord.getString('users_level')),
        users_tag: userRecord.getString('users_tag'),
        users_picture: userPicture.id,
        users_picture_url: userPicture.url,
        users_picture_attachment: userPicture.attachment,
        users_id_pic_a: userIdPicA.id,
        users_id_pic_a_url: userIdPicA.url,
        users_id_pic_a_attachment: userIdPicA.attachment,
        users_id_pic_b: userIdPicB.id,
        users_id_pic_b_url: userIdPicB.url,
        users_id_pic_b_attachment: userIdPicB.attachment,
        users_title_picture: userTitlePicture.id,
        users_title_picture_url: userTitlePicture.url,
        users_title_picture_attachment: userTitlePicture.attachment,
        openid: openid,
        company_id: companyId || '',
        users_parent_id: userRecord.getString('users_parent_id'),
        users_promo_code: userRecord.getString('users_promo_code'),
        usergroups_id: userRecord.getString('usergroups_id'),
        company: exportCompany(companyRecord),
        created: String(userRecord.created || ''),
        updated: String(userRecord.updated || ''),
    }
}

function buildAuthMeta(user) {
    return {
        statusCode: 200,
        errMsg: '操作成功',
        data: {
            status: user.status,
            is_info_complete: user.is_info_complete,
            user: user.user,
        },
    }
}

function ensureAuthIdentity(record) {
    if (!record.getString('email')) {
        const openid = record.getString('openid')
        if (openid) {
            record.set('email', openid + '@wechat.local')
        }
    }

    if (!record.getString('password')) {
        record.setPassword($security.randomString(24))
    }

    if (!record.getString('passwordConfirm')) {
        record.set('passwordConfirm', record.getString('password'))
    }
}

function ensureUserId(record) {
    if (!record.getString('users_id')) {
        record.set('users_id', buildUserId())
    }
}

function ensureUsersConversId(record) {
    if (!record.getString('users_convers_id')) {
        record.set('users_convers_id', buildUserConversId())
    }
}

function saveAuthUserRecord(record) {
    ensureUserId(record)
    ensureUsersConversId(record)
    ensureAuthIdentity(record)

    try {
        $app.save(record)
    } catch (err) {
        throw createAppError(400, '保存认证用户失败', {
            originalMessage: (err && err.message) || '未知错误',
            originalData: (err && err.data) || {},
        })
    }
}

function authenticateWechatUser(payload) {
    const openid = wechatService.getWxOpenId(payload.users_wx_code)

    return withUserLock('auth:' + openid, function () {
        const existing = findUserByOpenid(openid)
        if (existing) {
            logger.warn('微信注册命中已存在账号', {
                openid: openid,
                users_type: existing.getString('users_type') || GUEST_USER_TYPE,
            })

            const user = enrichUser(existing)

            return {
                status: 'login_success',
                is_info_complete: isInfoComplete(existing),
                user: user,
                authRecord: existing,
                authMethod: '',
                meta: buildAuthMeta({
                    status: 'login_success',
                    is_info_complete: isInfoComplete(existing),
                    user: user,
                }),
            }
        }

        const collection = $app.findCollectionByNameOrId('tbl_auth_users')
        const record = new Record(collection)
        record.set('openid', openid)
        record.set('users_idtype', WECHAT_ID_TYPE)
        record.set('users_type', GUEST_USER_TYPE)
        record.set('users_auth_type', 0)
        saveAuthUserRecord(record)

        const user = enrichUser(record)

        logger.info('微信用户注册成功', {
            users_id: user.users_id,
            users_type: user.users_type,
        })

        return {
            status: 'register_success',
            is_info_complete: false,
            user: user,
            authRecord: record,
            authMethod: '',
            meta: buildAuthMeta({
                status: 'register_success',
                is_info_complete: false,
                user: user,
            }),
        }
    })
}

function registerPlatformUser(payload) {
    return withUserLock('platform-register:' + payload.users_phone, function () {
        const existingPhoneUsers = $app.findRecordsByFilter('tbl_auth_users', 'users_phone = {:phone}', '', 10, 0, {
            phone: payload.users_phone,
        })

        for (let i = 0; i < existingPhoneUsers.length; i += 1) {
            if (existingPhoneUsers[i].getString('users_phone') === payload.users_phone) {
                throw createAppError(400, '手机号已被注册')
            }
        }

        const platformOpenid = buildGuid()
        const existingOpenid = findUserByOpenid(platformOpenid)
        if (existingOpenid) {
            throw createAppError(500, '生成平台用户唯一标识失败，请稍后重试')
        }

        const collection = $app.findCollectionByNameOrId('tbl_auth_users')
        const record = new Record(collection)

        record.set('openid', platformOpenid)
        record.set('users_idtype', MANAGE_PLATFORM_ID_TYPE)
        record.set('users_name', payload.users_name)
        record.set('users_phone', payload.users_phone)
        record.set('users_id_number', payload.users_id_number || '')
        record.set('users_type', payload.users_type || GUEST_USER_TYPE)
        record.set('users_tag', payload.users_tag || '')
        record.set('company_id', payload.company_id || '')
        record.set('users_parent_id', payload.users_parent_id || '')
        record.set('users_promo_code', payload.users_promo_code || '')
        record.set('usergroups_id', payload.usergroups_id || '')
        record.set('users_auth_type', 0)
        record.set('email', payload.email || (platformOpenid + '@manage.local'))
        record.setPassword(payload.password)
        record.set('passwordConfirm', payload.passwordConfirm)
        applyUserAttachmentFields(record, payload)

        saveAuthUserRecord(record)

        const user = enrichUser(record)

        logger.info('平台注册用户成功', {
            users_id: user.users_id,
            openid: user.openid,
            users_idtype: user.users_idtype,
        })

        return {
            status: 'register_success',
            is_info_complete: isInfoComplete(record),
            user: user,
            authRecord: record,
            authMethod: '',
            meta: buildAuthMeta({
                status: 'register_success',
                is_info_complete: isInfoComplete(record),
                user: user,
            }),
        }
    })
}

function authenticatePlatformUser(payload) {
    return withUserLock('platform-login:' + payload.login_account, function () {
        const loginAccount = String(payload.login_account || '')
        const userRecord = isEmail(loginAccount)
            ? findUserByEmail(loginAccount)
            : findUserByPhone(loginAccount)

        if (!userRecord) {
            throw createAppError(404, '平台用户不存在')
        }

        if (userRecord.getString('users_idtype') !== MANAGE_PLATFORM_ID_TYPE) {
            throw createAppError(400, '当前登录账号对应的不是平台用户')
        }

        const identity = userRecord.getString('email')
        if (!identity) {
            throw createAppError(500, '平台用户缺少原生登录标识')
        }

        const baseUrl = String(env.pocketbaseApiUrl || '').replace(/\/+$/, '')
        if (!baseUrl) {
            throw createAppError(500, '缺少 POCKETBASE_API_URL 配置')
        }

        const authResponse = $http.send({
            url: baseUrl + '/api/collections/tbl_auth_users/auth-with-password',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                identity: identity,
                password: payload.password,
            }),
        })

        if (!authResponse || authResponse.statusCode < 200 || authResponse.statusCode >= 300) {
            const responseBodyText = authResponse ? decodeHttpBodyText(authResponse.body) : ''
            let responseBody = {}

            try {
                responseBody = responseBodyText ? JSON.parse(responseBodyText) : {}
            } catch (_err) {
                responseBody = {}
            }

            const originalMessage = responseBody.message || ''
            const normalizedMessage = originalMessage === 'Something went wrong while processing your request.'
                ? '账号或密码错误'
                : (originalMessage || '平台登录失败')

            throw createAppError(400, normalizedMessage, {
                statusCode: authResponse ? authResponse.statusCode : 0,
                originalMessage: originalMessage,
                originalData: responseBody.data || {},
                body: responseBodyText,
            })
        }

        const authData = parseHttpJsonResponse(authResponse)
        const authRecord = userRecord

        const user = enrichUser(authRecord)

        logger.info('平台用户登录成功', {
            users_id: user.users_id,
            openid: user.openid,
            users_idtype: user.users_idtype,
            login_account: loginAccount,
        })

        return {
            status: 'login_success',
            is_info_complete: isInfoComplete(authRecord),
            user: user,
            authRecord: authRecord,
            authMethod: '',
            token: issueAuthToken(authRecord),
            pbRecord: authData.record || null,
            meta: buildAuthMeta({
                status: 'login_success',
                is_info_complete: isInfoComplete(authRecord),
                user: user,
            }),
        }
    })
}

function updateWechatUserProfile(usersWxOpenid, payload) {
    return withUserLock('profile:' + usersWxOpenid, function () {
        const currentUser = findUserByOpenid(usersWxOpenid)
        if (!currentUser) {
            throw createAppError(404, '未找到待编辑的用户')
        }

        const currentUserTypeBefore = currentUser.getString('users_type') || GUEST_USER_TYPE

        let usersPhone = ''
        if (payload.users_phone_code) {
            usersPhone = wechatService.getWxPhoneNumber(payload.users_phone_code)
        } else if (payload.users_phone) {
            usersPhone = String(payload.users_phone || '').trim()
        }

        if (usersPhone && usersPhone !== currentUser.getString('users_phone')) {
            const samePhoneUsers = $app.findRecordsByFilter('tbl_auth_users', 'users_phone = {:phone}', '', 10, 0, {
                phone: usersPhone,
            })
            for (let i = 0; i < samePhoneUsers.length; i += 1) {
                if (samePhoneUsers[i].id !== currentUser.id) {
                    throw createAppError(400, '手机号已被注册')
                }
            }
        }

        if (payload.users_name) {
            currentUser.set('users_name', payload.users_name)
        }
        if (usersPhone) {
            currentUser.set('users_phone', usersPhone)
        }
        let hasExplicitUserType = false
        if (typeof payload.users_type !== 'undefined' && payload.users_type) {
            const requestedUserType = String(payload.users_type || '').trim()
            if (requestedUserType) {
                currentUser.set('users_type', requestedUserType)
                hasExplicitUserType = true
            }
        }
        if (typeof payload.company_id !== 'undefined' && payload.company_id) {
            currentUser.set('company_id', payload.company_id)
        }
        if (typeof payload.users_tag !== 'undefined' && payload.users_tag) {
            currentUser.set('users_tag', payload.users_tag)
        }
        applyUserAttachmentFields(currentUser, payload)

        const shouldPromote = (currentUserTypeBefore === GUEST_USER_TYPE)
            && !hasExplicitUserType
        if (shouldPromote) {
            currentUser.set('users_type', REGISTERED_USER_TYPE)
        }

        saveAuthUserRecord(currentUser)

        const user = enrichUser(currentUser)

        logger.info('微信用户资料更新成功', {
            users_id: user.users_id,
            users_type_after: user.users_type,
            users_type_promoted: shouldPromote,
        })

        return {
            status: 'update_success',
            user: user,
        }
    })
}

function updateManagedUserProfile(payload) {
    return withUserLock('manage-user-update:' + payload.openid, function () {
        const currentUser = findUserByOpenid(payload.openid)
        if (!currentUser) {
            throw createAppError(404, '未找到待编辑的用户')
        }

        const nextPhone = Object.prototype.hasOwnProperty.call(payload, 'users_phone')
            ? normalizeText(payload.users_phone)
            : undefined

        if (typeof nextPhone !== 'undefined' && nextPhone && nextPhone !== currentUser.getString('users_phone')) {
            const samePhoneUsers = $app.findRecordsByFilter('tbl_auth_users', 'users_phone = {:phone}', '', 10, 0, {
                phone: nextPhone,
            })

            for (let i = 0; i < samePhoneUsers.length; i += 1) {
                if (samePhoneUsers[i].id !== currentUser.id) {
                    throw createAppError(400, '手机号已被注册')
                }
            }
        }

        if (Object.prototype.hasOwnProperty.call(payload, 'users_name')) {
            currentUser.set('users_name', normalizeText(payload.users_name))
        }
        if (typeof nextPhone !== 'undefined') {
            currentUser.set('users_phone', nextPhone)
        }
        if (Object.prototype.hasOwnProperty.call(payload, 'users_id_number')) {
            currentUser.set('users_id_number', normalizeText(payload.users_id_number))
        }
        if (Object.prototype.hasOwnProperty.call(payload, 'users_level')) {
            currentUser.set('users_level', ensureValidUserLevel(payload.users_level))
        }
        if (Object.prototype.hasOwnProperty.call(payload, 'users_type')) {
            currentUser.set('users_type', normalizeText(payload.users_type))
        }
        if (Object.prototype.hasOwnProperty.call(payload, 'users_tag')) {
            currentUser.set('users_tag', normalizeText(payload.users_tag))
        }
        if (Object.prototype.hasOwnProperty.call(payload, 'company_id')) {
            currentUser.set('company_id', normalizeText(payload.company_id))
        }
        if (Object.prototype.hasOwnProperty.call(payload, 'users_parent_id')) {
            currentUser.set('users_parent_id', normalizeText(payload.users_parent_id))
        }
        if (Object.prototype.hasOwnProperty.call(payload, 'users_promo_code')) {
            currentUser.set('users_promo_code', normalizeText(payload.users_promo_code))
        }
        if (Object.prototype.hasOwnProperty.call(payload, 'usergroups_id')) {
            currentUser.set('usergroups_id', normalizeText(payload.usergroups_id))
        }
        if (Object.prototype.hasOwnProperty.call(payload, 'users_status')) {
            currentUser.set('users_status', normalizeText(payload.users_status))
        }
        if (Object.prototype.hasOwnProperty.call(payload, 'users_rank_level')) {
            currentUser.set('users_rank_level', normalizeOptionalNumber(payload.users_rank_level, 'users_rank_level'))
        }
        if (Object.prototype.hasOwnProperty.call(payload, 'users_auth_type')) {
            currentUser.set('users_auth_type', normalizeOptionalNumber(payload.users_auth_type, 'users_auth_type'))
        }

        applyUserAttachmentFields(currentUser, payload)
        if (Object.prototype.hasOwnProperty.call(payload, 'users_picture') && !normalizeText(payload.users_picture)) {
            currentUser.set('users_picture', '')
        }
        if (Object.prototype.hasOwnProperty.call(payload, 'users_id_pic_a') && !normalizeText(payload.users_id_pic_a)) {
            currentUser.set('users_id_pic_a', '')
        }
        if (Object.prototype.hasOwnProperty.call(payload, 'users_id_pic_b') && !normalizeText(payload.users_id_pic_b)) {
            currentUser.set('users_id_pic_b', '')
        }
        if (Object.prototype.hasOwnProperty.call(payload, 'users_title_picture') && !normalizeText(payload.users_title_picture)) {
            currentUser.set('users_title_picture', '')
        }

        saveAuthUserRecord(currentUser)

        const user = enrichUser(currentUser)

        logger.info('管理端更新用户资料成功', {
            users_id: user.users_id,
            openid: user.openid,
        })

        return {
            status: 'update_success',
            user: user,
        }
    })
}

function refreshAuthToken(openid) {
    const userRecord = findUserByOpenid(openid)
    if (!userRecord) {
        throw createAppError(404, '未注册用户')
    }

    logger.info('认证用户刷新令牌成功', {
        users_id: userRecord.getString('users_id'),
        users_convers_id: userRecord.getString('users_convers_id'),
        openid: userRecord.getString('openid'),
    })

    return {
        authRecord: userRecord,
        authMethod: '',
        meta: {
            statusCode: 200,
            errMsg: '刷新成功',
            data: {},
        },
    }
}

function issueAuthToken(authRecord) {
    if (!authRecord) {
        throw createAppError(500, '签发令牌失败：认证用户不存在')
    }

    if (typeof authRecord.newAuthToken !== 'function') {
        throw createAppError(500, '签发令牌失败：当前运行环境不支持 newAuthToken')
    }

    const token = authRecord.newAuthToken()
    if (!token) {
        throw createAppError(500, '签发令牌失败：生成 token 为空')
    }

    return token
}

function ensureAuthToken(token) {
    if (!token) {
        throw createAppError(500, '签发令牌失败：生成 token 为空')
    }

    return token
}

module.exports = {
    authenticateWechatUser,
    authenticatePlatformUser,
    ensureAuthToken,
    updateWechatUserProfile,
    updateManagedUserProfile,
    refreshAuthToken,
    issueAuthToken,
    registerPlatformUser,
    resolveUserLevelName,
    getUserLevelOptions,
}

