const { createAppError } = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/appError.js`)
const { sanitizePayload } = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/sanitize.js`)

const requestCache = {}
const WINDOW_MS = 5000

function parseBody(e) {
    return sanitizePayload(e.requestInfo().body || {})
}

function requireJson(e) {
    const contentType = e.request.header.get('Content-Type') || e.request.header.get('content-type') || ''
    if (contentType.toLowerCase().indexOf('application/json') === -1) {
        throw createAppError(415, '请求体必须为 application/json')
    }
}

function validateLoginBody(e) {
    const payload = parseBody(e)
    if (!payload.users_wx_code) {
        throw createAppError(400, 'users_wx_code 为必填项')
    }
    return payload
}

function validateProfileBody(e) {
    const payload = parseBody(e)
    return {
        users_name: Object.prototype.hasOwnProperty.call(payload, 'users_name') ? String(payload.users_name || '').trim() : undefined,
        users_phone_code: Object.prototype.hasOwnProperty.call(payload, 'users_phone_code') ? String(payload.users_phone_code || '').trim() : undefined,
        users_phone: Object.prototype.hasOwnProperty.call(payload, 'users_phone') ? String(payload.users_phone || '').trim() : undefined,
        users_type: Object.prototype.hasOwnProperty.call(payload, 'users_type') ? String(payload.users_type || '').trim() : undefined,
        company_id: Object.prototype.hasOwnProperty.call(payload, 'company_id') ? String(payload.company_id || '').trim() : undefined,
        users_tag: Object.prototype.hasOwnProperty.call(payload, 'users_tag') ? String(payload.users_tag || '').trim() : undefined,
        users_picture: Object.prototype.hasOwnProperty.call(payload, 'users_picture') ? String(payload.users_picture || '').trim() : undefined,
        users_id_pic_a: Object.prototype.hasOwnProperty.call(payload, 'users_id_pic_a') ? payload.users_id_pic_a : undefined,
        users_id_pic_b: Object.prototype.hasOwnProperty.call(payload, 'users_id_pic_b') ? payload.users_id_pic_b : undefined,
        users_title_picture: Object.prototype.hasOwnProperty.call(payload, 'users_title_picture') ? payload.users_title_picture : undefined,
    }
}

function validatePlatformRegisterBody(e) {
    const payload = parseBody(e)

    if (!payload.users_name) throw createAppError(400, 'users_name 为必填项')
    if (!payload.users_phone) throw createAppError(400, 'users_phone 为必填项')
    if (!payload.password) throw createAppError(400, 'password 为必填项')
    if (!payload.passwordConfirm) throw createAppError(400, 'passwordConfirm 为必填项')
    if (!payload.users_picture) throw createAppError(400, 'users_picture 为必填项')

    if (payload.password !== payload.passwordConfirm) {
        throw createAppError(400, 'password 与 passwordConfirm 不一致')
    }

    return {
        users_name: payload.users_name,
        users_phone: payload.users_phone,
        password: payload.password,
        passwordConfirm: payload.passwordConfirm,
        users_picture: payload.users_picture,
        users_id_number: payload.users_id_number || '',
        users_level: payload.users_level || '',
        users_type: payload.users_type || '',
        users_tag: payload.users_tag || '',
        company_id: payload.company_id || '',
        users_parent_id: payload.users_parent_id || '',
        users_promo_code: payload.users_promo_code || '',
        usergroups_id: payload.usergroups_id || '',
        email: payload.email || '',
        users_id_pic_a: Object.prototype.hasOwnProperty.call(payload, 'users_id_pic_a') ? payload.users_id_pic_a : undefined,
        users_id_pic_b: Object.prototype.hasOwnProperty.call(payload, 'users_id_pic_b') ? payload.users_id_pic_b : undefined,
        users_title_picture: Object.prototype.hasOwnProperty.call(payload, 'users_title_picture') ? payload.users_title_picture : undefined,
    }
}

function validatePlatformLoginBody(e) {
    const payload = parseBody(e)

    const loginAccount = String(payload.login_account || payload.users_phone || payload.email || '').trim()
    const password = String(payload.password || '')

    if (!loginAccount) throw createAppError(400, 'login_account 为必填项，支持邮箱或手机号')
    if (!password) throw createAppError(400, 'password 为必填项')

    return {
        login_account: loginAccount,
        password: password,
    }
}

function validateSystemRefreshBody(e) {
    const payload = parseBody(e)

    if (typeof payload.users_wx_code === 'undefined' || payload.users_wx_code === null) {
        return {
            users_wx_code: '',
        }
    }

    if (typeof payload.users_wx_code !== 'string') {
        throw createAppError(400, 'users_wx_code 类型错误')
    }

    return {
        users_wx_code: payload.users_wx_code,
    }
}

function requireManagePlatformUser(e) {
    const authHeader = e.request.header.get('Authorization') || ''
    const parts = authHeader.split(' ')

    if (parts.length !== 2 || parts[0] !== 'Bearer' || !parts[1]) {
        throw createAppError(401, '请求头缺少 Authorization')
    }

    if (!e.auth) {
        throw createAppError(401, '认证令牌无效或已过期')
    }

    if (e.auth.collection().name !== 'tbl_auth_users') {
        throw createAppError(401, '认证用户集合不正确')
    }

    const authRecord = e.auth
    const idType = authRecord.getString('users_idtype')

    if (idType !== 'ManagePlatform') {
        throw createAppError(403, '仅平台管理用户可访问')
    }

    return {
        openid: authRecord.getString('openid') || '',
        authRecord: authRecord,
    }
}

function validateDictionaryListBody(e) {
    const payload = parseBody(e)
    return {
        keyword: payload.keyword || '',
    }
}

function validateDictionaryDetailBody(e) {
    const payload = parseBody(e)
    if (!payload.dict_name) {
        throw createAppError(400, 'dict_name 为必填项')
    }

    return {
        dict_name: payload.dict_name,
    }
}

function normalizeDictionaryItem(item, index) {
    const current = sanitizePayload(item || {})
    if (!current.enum) {
        throw createAppError(400, '第 ' + (index + 1) + ' 项 enum 为必填项')
    }

    if (!current.description) {
        throw createAppError(400, '第 ' + (index + 1) + ' 项 description 为必填项')
    }

    const sortOrderNumber = Number(current.sortOrder)
    if (!Number.isFinite(sortOrderNumber)) {
        throw createAppError(400, '第 ' + (index + 1) + ' 项 sortOrder 必须为数字')
    }

    const imageIdList = normalizeAttachmentIdList(current.image, '第 ' + (index + 1) + ' 项 image')

    return {
        enum: String(current.enum),
        description: String(current.description),
        sortOrder: sortOrderNumber,
        image: imageIdList.join('|'),
    }
}

function validateDictionaryMutationBody(e, isUpdate) {
    const payload = parseBody(e)

    if (!payload.dict_name) {
        throw createAppError(400, 'dict_name 为必填项')
    }

    const items = Array.isArray(payload.items) ? payload.items : []
    if (!items.length) {
        throw createAppError(400, 'items 至少需要一项')
    }

    const normalizedItems = items.map(function (item, index) {
        return normalizeDictionaryItem(item, index)
    })

    return {
        dict_name: payload.dict_name,
        dict_word_is_enabled: typeof payload.dict_word_is_enabled === 'boolean' ? payload.dict_word_is_enabled : true,
        dict_word_parent_id: payload.dict_word_parent_id || '',
        dict_word_remark: payload.dict_word_remark || '',
        items: normalizedItems,
        original_dict_name: isUpdate ? (payload.original_dict_name || payload.dict_name) : '',
    }
}

function validateDictionaryDeleteBody(e) {
    const payload = parseBody(e)
    if (!payload.dict_name) {
        throw createAppError(400, 'dict_name 为必填项')
    }

    return {
        dict_name: payload.dict_name,
    }
}

function validateAttachmentListBody(e) {
    const payload = parseBody(e)

    return {
        keyword: payload.keyword || '',
        status: payload.status || '',
    }
}

function validateAttachmentDetailBody(e) {
    const payload = parseBody(e)
    if (!payload.attachments_id) {
        throw createAppError(400, 'attachments_id 为必填项')
    }

    return {
        attachments_id: payload.attachments_id,
    }
}

function validateAttachmentDeleteBody(e) {
    return validateAttachmentDetailBody(e)
}

function validateAttachmentUploadBody(e) {
    const request = e.request
    if (request && typeof request.parseMultipartForm === 'function') {
        // Explicit multipart parsing avoids the default Request.ParseForm 10MB cap path.
        request.parseMultipartForm(64 * 1024 * 1024)
    }

    const payload = sanitizePayload({
        attachments_filename: request && typeof request.postFormValue === 'function' ? request.postFormValue('attachments_filename') : '',
        attachments_filetype: request && typeof request.postFormValue === 'function' ? request.postFormValue('attachments_filetype') : '',
        attachments_size: request && typeof request.postFormValue === 'function' ? request.postFormValue('attachments_size') : 0,
        attachments_md5: request && typeof request.postFormValue === 'function' ? request.postFormValue('attachments_md5') : '',
        attachments_ocr: request && typeof request.postFormValue === 'function' ? request.postFormValue('attachments_ocr') : '',
        attachments_status: request && typeof request.postFormValue === 'function' ? request.postFormValue('attachments_status') : '',
        attachments_remark: request && typeof request.postFormValue === 'function' ? request.postFormValue('attachments_remark') : '',
    })

    return {
        attachments_filename: payload.attachments_filename || '',
        attachments_filetype: payload.attachments_filetype || '',
        attachments_size: payload.attachments_size || 0,
        attachments_md5: payload.attachments_md5 || '',
        attachments_ocr: payload.attachments_ocr || '',
        attachments_status: payload.attachments_status || 'active',
        attachments_remark: payload.attachments_remark || '',
    }
}

function validateDocumentListBody(e) {
    const payload = parseBody(e)

    return {
        keyword: payload.keyword || '',
        status: payload.status || '',
        document_type: payload.document_type || '',
    }
}

function validateDocumentDetailBody(e) {
    const payload = parseBody(e)
    if (!payload.document_id) {
        throw createAppError(400, 'document_id 为必填项')
    }

    return {
        document_id: payload.document_id,
    }
}

function normalizeAttachmentIdList(value, fieldName) {
    if (Array.isArray(value)) {
        return value
            .map(function (item) {
                return String(item || '').trim()
            })
            .filter(function (item) {
                return !!item
            })
    }

    if (typeof value === 'undefined' || value === null || value === '') {
        return []
    }

    if (typeof value !== 'string') {
        throw createAppError(400, fieldName + ' 类型错误，需为字符串或数组')
    }

    return value
        .split('|')
        .map(function (item) {
            return String(item || '').trim()
        })
        .filter(function (item) {
            return !!item
        })
}

function validateDocumentMutationBody(e, isUpdate) {
    const payload = parseBody(e)

    if (!payload.document_id && isUpdate) {
        throw createAppError(400, 'document_id 为必填项')
    }

    if (!payload.document_title) {
        throw createAppError(400, 'document_title 为必填项')
    }

    if (!payload.document_type) {
        throw createAppError(400, 'document_type 为必填项')
    }

    return {
        document_id: payload.document_id || '',
        document_effect_date: payload.document_effect_date || '',
        document_expiry_date: payload.document_expiry_date || '',
        document_type: payload.document_type || '',
        document_title: payload.document_title || '',
        document_subtitle: payload.document_subtitle || '',
        document_summary: payload.document_summary || '',
        document_content: payload.document_content || '',
        document_image: normalizeAttachmentIdList(payload.document_image, 'document_image'),
        document_video: normalizeAttachmentIdList(payload.document_video, 'document_video'),
        document_file: normalizeAttachmentIdList(payload.document_file, 'document_file'),
        document_relation_model: payload.document_relation_model || '',
        document_keywords: payload.document_keywords || '',
        document_share_count: typeof payload.document_share_count === 'undefined' ? '' : payload.document_share_count,
        document_download_count: typeof payload.document_download_count === 'undefined' ? '' : payload.document_download_count,
        document_favorite_count: typeof payload.document_favorite_count === 'undefined' ? '' : payload.document_favorite_count,
        document_status: payload.document_status || '',
        document_embedding_status: payload.document_embedding_status || '',
        document_embedding_error: payload.document_embedding_error || '',
        document_embedding_lasttime: payload.document_embedding_lasttime || '',
        document_vector_version: payload.document_vector_version || '',
        document_product_categories: payload.document_product_categories || '',
        document_application_scenarios: payload.document_application_scenarios || '',
        document_hotel_type: payload.document_hotel_type || '',
        document_remark: payload.document_remark || '',
    }
}

function validateDocumentDeleteBody(e) {
    return validateDocumentDetailBody(e)
}

function normalizeProductParameters(value) {
    if (value === null || typeof value === 'undefined' || value === '') {
        return []
    }

    const result = []
    const indexByName = {}

    function normalizeParameterSort(rawSort, fallbackSort) {
        if (rawSort === '' || rawSort === null || typeof rawSort === 'undefined') {
            return fallbackSort
        }

        const num = Number(rawSort)
        if (!Number.isFinite(num) || num <= 0 || Math.floor(num) !== num) {
            throw createAppError(400, 'prod_list_parameters.sort 必须为正整数')
        }

        return num
    }

    function upsert(nameValue, rawValue, rawSort, fallbackSort) {
        const name = String(nameValue || '').trim()
        if (!name) {
            return
        }

        const normalizedValue = rawValue === null || typeof rawValue === 'undefined' ? '' : String(rawValue)
        const normalizedSort = normalizeParameterSort(rawSort, fallbackSort)
        const existingIndex = indexByName[name]
        if (typeof existingIndex === 'number') {
            result[existingIndex].value = normalizedValue
            result[existingIndex].sort = normalizedSort
            return
        }

        indexByName[name] = result.length
        result.push({
            name: name,
            value: normalizedValue,
            sort: normalizedSort,
        })
    }

    if (Array.isArray(value)) {
        for (let i = 0; i < value.length; i += 1) {
            const item = value[i] && typeof value[i] === 'object' ? value[i] : null
            if (!item) {
                continue
            }
            upsert(item.name || item.key, item.value, item.sort, result.length + 1)
        }
        return result
    }

    if (typeof value !== 'object') {
        throw createAppError(400, 'prod_list_parameters 必须为数组或对象')
    }

    const keys = Object.keys(value)

    for (let i = 0; i < keys.length; i += 1) {
        upsert(keys[i], value[keys[i]], '', result.length + 1)
    }

    return result
}

function normalizeProductVipPrice(value) {
    if (value === null || typeof value === 'undefined' || value === '') {
        return []
    }

    let source = value
    if (typeof source === 'string') {
        try {
            source = JSON.parse(source)
        } catch (_error) {
            throw createAppError(400, 'prod_list_vip_price 必须为合法 JSON 数组')
        }
    }

    if (!Array.isArray(source)) {
        throw createAppError(400, 'prod_list_vip_price 必须为数组')
    }

    const result = []
    const levelMap = {}

    for (let i = 0; i < source.length; i += 1) {
        const item = source[i] && typeof source[i] === 'object' ? source[i] : null
        if (!item) {
            continue
        }

        const viplevel = String(item.viplevel || '').trim()
        if (!viplevel) {
            throw createAppError(400, 'prod_list_vip_price 第 ' + (i + 1) + ' 项 viplevel 为必填项')
        }

        const price = Number(item.price)
        if (!Number.isFinite(price)) {
            throw createAppError(400, 'prod_list_vip_price 第 ' + (i + 1) + ' 项 price 必须为数字')
        }

        if (levelMap[viplevel]) {
            throw createAppError(400, 'prod_list_vip_price 中 viplevel 不允许重复：' + viplevel)
        }

        levelMap[viplevel] = true
        result.push({
            viplevel: viplevel,
            price: price,
        })
    }

    return result
}

function validateProductListBody(e) {
    const payload = parseBody(e)

    return {
        keyword: payload.keyword || '',
        status: payload.status || '',
        prod_list_category: payload.prod_list_category || '',
    }
}

function validateProductDetailBody(e) {
    const payload = parseBody(e)
    if (!payload.prod_list_id) {
        throw createAppError(400, 'prod_list_id 为必填项')
    }

    return {
        prod_list_id: String(payload.prod_list_id || '').trim(),
    }
}

function validateProductMutationBody(e, isUpdate) {
    const payload = parseBody(e)

    if (isUpdate && !payload.prod_list_id) {
        throw createAppError(400, 'prod_list_id 为必填项')
    }

    if (!payload.prod_list_name) {
        throw createAppError(400, 'prod_list_name 为必填项')
    }

    if (!payload.prod_list_category) {
        throw createAppError(400, 'prod_list_category 为必填项')
    }

    return {
        id: payload.id || '',
        prod_list_id: payload.prod_list_id || '',
        prod_list_name: payload.prod_list_name || '',
        prod_list_modelnumber: payload.prod_list_modelnumber || '',
        prod_list_barcode: payload.prod_list_barcode || '',
        prod_list_icon: normalizeAttachmentIdList(payload.prod_list_icon, 'prod_list_icon').join('|'),
        prod_list_description: payload.prod_list_description || '',
        prod_list_feature: payload.prod_list_feature || '',
        prod_list_parameters: normalizeProductParameters(payload.prod_list_parameters),
        prod_list_function: normalizeProductParameters(payload.prod_list_function),
        prod_list_plantype: payload.prod_list_plantype || '',
        prod_list_category: payload.prod_list_category || '',
        prod_list_sort: typeof payload.prod_list_sort === 'undefined' ? 0 : payload.prod_list_sort,
        prod_list_comm_type: payload.prod_list_comm_type || '',
        prod_list_series: payload.prod_list_series || '',
        prod_list_power_supply: payload.prod_list_power_supply || '',
        prod_list_tags: payload.prod_list_tags || '',
        prod_list_status: payload.prod_list_status || '',
        prod_list_basic_price: typeof payload.prod_list_basic_price === 'undefined' ? '' : payload.prod_list_basic_price,
        prod_list_vip_price: normalizeProductVipPrice(payload.prod_list_vip_price),
        prod_list_remark: payload.prod_list_remark || '',
    }
}

function validateProductDeleteBody(e) {
    return validateProductDetailBody(e)
}

function validateSchemeTemplateListBody(e) {
    const payload = parseBody(e)

    return {
        keyword: payload.keyword || '',
        scheme_template_owner: payload.scheme_template_owner || '',
        scheme_template_status: payload.scheme_template_status || '',
        scheme_template_solution_type: payload.scheme_template_solution_type || '',
        scheme_template_solution_feature: payload.scheme_template_solution_feature || '',
    }
}

function validateSchemeTemplateDetailBody(e) {
    const payload = parseBody(e)
    if (!payload.scheme_template_id) {
        throw createAppError(400, 'scheme_template_id 为必填项')
    }

    return {
        scheme_template_id: String(payload.scheme_template_id || '').trim(),
    }
}

function validateSchemeTemplateMutationBody(e, isUpdate) {
    const payload = parseBody(e)

    if (isUpdate && !payload.scheme_template_id) {
        throw createAppError(400, 'scheme_template_id 为必填项')
    }

    if (!payload.scheme_template_name) {
        throw createAppError(400, 'scheme_template_name 为必填项')
    }

    if (!payload.scheme_template_owner) {
        throw createAppError(400, 'scheme_template_owner 为必填项')
    }

    return {
        scheme_template_id: payload.scheme_template_id || '',
        scheme_template_icon: Object.prototype.hasOwnProperty.call(payload, 'scheme_template_icon') ? payload.scheme_template_icon : '',
        scheme_template_label: payload.scheme_template_label || '',
        scheme_template_name: payload.scheme_template_name || '',
        scheme_template_owner: payload.scheme_template_owner || '',
        scheme_template_status: payload.scheme_template_status || '',
        scheme_template_solution_type: payload.scheme_template_solution_type || '',
        scheme_template_solution_feature: payload.scheme_template_solution_feature || '',
        scheme_template_product_list: Object.prototype.hasOwnProperty.call(payload, 'scheme_template_product_list') ? payload.scheme_template_product_list : [],
        scheme_template_description: payload.scheme_template_description || '',
        scheme_template_remark: payload.scheme_template_remark || '',
    }
}

function validateSchemeTemplateDeleteBody(e) {
    return validateSchemeTemplateDetailBody(e)
}

function validateSchemeListBody(e) {
    const payload = parseBody(e)

    return {
        keyword: payload.keyword || '',
        scheme_owner: payload.scheme_owner || '',
        scheme_status: payload.scheme_status || '',
        scheme_share_status: payload.scheme_share_status || '',
        scheme_hotel_type: payload.scheme_hotel_type || '',
    }
}

function validateSchemeDetailBody(e) {
    const payload = parseBody(e)
    if (!payload.scheme_id) {
        throw createAppError(400, 'scheme_id 为必填项')
    }

    return {
        scheme_id: String(payload.scheme_id || '').trim(),
    }
}

function validateSchemeMutationBody(e, isUpdate) {
    const payload = parseBody(e)

    if (isUpdate && !payload.scheme_id) {
        throw createAppError(400, 'scheme_id 为必填项')
    }

    if (!payload.scheme_name) {
        throw createAppError(400, 'scheme_name 为必填项')
    }

    if (!payload.scheme_owner) {
        throw createAppError(400, 'scheme_owner 为必填项')
    }

    return {
        scheme_id: payload.scheme_id || '',
        scheme_name: payload.scheme_name || '',
        scheme_owner: payload.scheme_owner || '',
        scheme_share_status: payload.scheme_share_status || '',
        scheme_expires_at: payload.scheme_expires_at || '',
        scheme_hotel_type: payload.scheme_hotel_type || '',
        scheme_solution_type: payload.scheme_solution_type || '',
        scheme_solution_feature: payload.scheme_solution_feature || '',
        scheme_room_type: Object.prototype.hasOwnProperty.call(payload, 'scheme_room_type') ? payload.scheme_room_type : [],
        scheme_curtains: payload.scheme_curtains || '',
        scheme_voice_device: payload.scheme_voice_device || '',
        scheme_ac_type: payload.scheme_ac_type || '',
        scheme_template_highend: payload.scheme_template_highend || '',
        scheme_template_midend: payload.scheme_template_midend || '',
        scheme_template_lowend: payload.scheme_template_lowend || '',
        scheme_status: payload.scheme_status || '',
        scheme_remark: payload.scheme_remark || '',
    }
}

function validateSchemeDeleteBody(e) {
    return validateSchemeDetailBody(e)
}

function validateCartListBody(e) {
    const payload = parseBody(e)

    return {
        keyword: payload.keyword || '',
        cart_status: payload.cart_status || '',
        cart_number: payload.cart_number || '',
    }
}

function validateCartDetailBody(e) {
    const payload = parseBody(e)
    if (!payload.cart_id) {
        throw createAppError(400, 'cart_id 为必填项')
    }

    return {
        cart_id: String(payload.cart_id || '').trim(),
    }
}

function validateCartMutationBody(e, isUpdate) {
    const payload = parseBody(e)

    if (isUpdate && !payload.cart_id) {
        throw createAppError(400, 'cart_id 为必填项')
    }

    if (!isUpdate) {
        if (!payload.cart_product_id) {
            throw createAppError(400, 'cart_product_id 为必填项，且必须传 tbl_product_list 的 recordId')
        }
        if (typeof payload.cart_product_quantity === 'undefined') {
            throw createAppError(400, 'cart_product_quantity 为必填项')
        }
        if (typeof payload.cart_at_price === 'undefined') {
            throw createAppError(400, 'cart_at_price 为必填项')
        }
    }

    return {
        cart_id: payload.cart_id || '',
        cart_number: Object.prototype.hasOwnProperty.call(payload, 'cart_number') ? payload.cart_number : undefined,
        cart_owner: Object.prototype.hasOwnProperty.call(payload, 'cart_owner') ? payload.cart_owner : undefined,
        cart_product_id: Object.prototype.hasOwnProperty.call(payload, 'cart_product_id') ? payload.cart_product_id : undefined,
        cart_product_quantity: Object.prototype.hasOwnProperty.call(payload, 'cart_product_quantity') ? payload.cart_product_quantity : undefined,
        cart_status: Object.prototype.hasOwnProperty.call(payload, 'cart_status') ? payload.cart_status : undefined,
        cart_at_price: Object.prototype.hasOwnProperty.call(payload, 'cart_at_price') ? payload.cart_at_price : undefined,
        cart_remark: Object.prototype.hasOwnProperty.call(payload, 'cart_remark') ? payload.cart_remark : undefined,
    }
}

function validateCartDeleteBody(e) {
    return validateCartDetailBody(e)
}

function validateOrderListBody(e) {
    const payload = parseBody(e)

    return {
        keyword: payload.keyword || '',
        order_status: payload.order_status || '',
        order_source: payload.order_source || '',
    }
}

function validateOrderDetailBody(e) {
    const payload = parseBody(e)
    if (!payload.order_id) {
        throw createAppError(400, 'order_id 为必填项')
    }

    return {
        order_id: String(payload.order_id || '').trim(),
    }
}

function validateOrderMutationBody(e, isUpdate) {
    const payload = parseBody(e)

    if (isUpdate && !payload.order_id) {
        throw createAppError(400, 'order_id 为必填项')
    }

    if (!isUpdate) {
        if (!payload.order_source) {
            throw createAppError(400, 'order_source 为必填项')
        }
        if (!payload.order_source_id) {
            throw createAppError(400, 'order_source_id 为必填项')
        }
        if (typeof payload.order_snap === 'undefined') {
            throw createAppError(400, 'order_snap 为必填项')
        }
        if (typeof payload.order_amount === 'undefined') {
            throw createAppError(400, 'order_amount 为必填项')
        }
    }

    return {
        order_id: payload.order_id || '',
        order_number: Object.prototype.hasOwnProperty.call(payload, 'order_number') ? payload.order_number : undefined,
        order_owner: Object.prototype.hasOwnProperty.call(payload, 'order_owner') ? payload.order_owner : undefined,
        order_source: Object.prototype.hasOwnProperty.call(payload, 'order_source') ? payload.order_source : undefined,
        order_status: Object.prototype.hasOwnProperty.call(payload, 'order_status') ? payload.order_status : undefined,
        order_source_id: Object.prototype.hasOwnProperty.call(payload, 'order_source_id') ? payload.order_source_id : undefined,
        order_snap: Object.prototype.hasOwnProperty.call(payload, 'order_snap') ? payload.order_snap : undefined,
        order_amount: Object.prototype.hasOwnProperty.call(payload, 'order_amount') ? payload.order_amount : undefined,
        order_remark: Object.prototype.hasOwnProperty.call(payload, 'order_remark') ? payload.order_remark : undefined,
    }
}

function validateOrderDeleteBody(e) {
    return validateOrderDetailBody(e)
}

function validateCartOrderManageListBody(e) {
    const payload = parseBody(e)
    return {
        keyword: payload.keyword || '',
    }
}

function validateCartOrderManageUserUpdateBody(e) {
    const payload = parseBody(e)
    if (!payload.openid) {
        throw createAppError(400, 'openid 为必填项')
    }

    return {
        openid: String(payload.openid || '').trim(),
        users_name: Object.prototype.hasOwnProperty.call(payload, 'users_name') ? payload.users_name : undefined,
        users_phone: Object.prototype.hasOwnProperty.call(payload, 'users_phone') ? payload.users_phone : undefined,
        users_id_number: Object.prototype.hasOwnProperty.call(payload, 'users_id_number') ? payload.users_id_number : undefined,
        users_level: Object.prototype.hasOwnProperty.call(payload, 'users_level') ? payload.users_level : undefined,
        users_type: Object.prototype.hasOwnProperty.call(payload, 'users_type') ? payload.users_type : undefined,
        users_tag: Object.prototype.hasOwnProperty.call(payload, 'users_tag') ? payload.users_tag : undefined,
        users_status: Object.prototype.hasOwnProperty.call(payload, 'users_status') ? payload.users_status : undefined,
        users_rank_level: Object.prototype.hasOwnProperty.call(payload, 'users_rank_level') ? payload.users_rank_level : undefined,
        users_auth_type: Object.prototype.hasOwnProperty.call(payload, 'users_auth_type') ? payload.users_auth_type : undefined,
        company_id: Object.prototype.hasOwnProperty.call(payload, 'company_id') ? payload.company_id : undefined,
        users_parent_id: Object.prototype.hasOwnProperty.call(payload, 'users_parent_id') ? payload.users_parent_id : undefined,
        users_promo_code: Object.prototype.hasOwnProperty.call(payload, 'users_promo_code') ? payload.users_promo_code : undefined,
        usergroups_id: Object.prototype.hasOwnProperty.call(payload, 'usergroups_id') ? payload.usergroups_id : undefined,
        users_picture: Object.prototype.hasOwnProperty.call(payload, 'users_picture') ? payload.users_picture : undefined,
        users_id_pic_a: Object.prototype.hasOwnProperty.call(payload, 'users_id_pic_a') ? payload.users_id_pic_a : undefined,
        users_id_pic_b: Object.prototype.hasOwnProperty.call(payload, 'users_id_pic_b') ? payload.users_id_pic_b : undefined,
        users_title_picture: Object.prototype.hasOwnProperty.call(payload, 'users_title_picture') ? payload.users_title_picture : undefined,
    }
}

function validateDocumentHistoryListBody(e) {
    const payload = parseBody(e)

    return {
        document_id: payload.document_id || '',
    }
}

function normalizeRuleConfig(input) {
    const current = sanitizePayload(input || {})
    const mode = String(current.mode || 'locked')
    const rawExpression = String(current.rawExpression || '')
    const roles = Array.isArray(current.roles)
        ? current.roles.map(function (item) {
            return String(item || '').trim()
        }).filter(function (item) {
            return !!item
        })
        : []

    return {
        mode: mode,
        includeManagePlatform: !!current.includeManagePlatform,
        roles: roles,
        rawExpression: rawExpression,
    }
}

function validateSdkPermissionContextBody(e) {
    const payload = parseBody(e)
    return {
        keyword: payload.keyword || '',
    }
}

function validateSdkPermissionRoleBody(e) {
    const payload = parseBody(e)
    if (!payload.role_name) {
        throw createAppError(400, 'role_name 为必填项')
    }

    return {
        original_role_id: payload.original_role_id || '',
        role_id: payload.role_id || '',
        role_name: payload.role_name,
        role_code: payload.role_code || '',
        role_status: typeof payload.role_status === 'undefined' ? 1 : payload.role_status,
        role_remark: payload.role_remark || '',
    }
}

function validateSdkPermissionRoleDeleteBody(e) {
    const payload = parseBody(e)
    if (!payload.role_id) {
        throw createAppError(400, 'role_id 为必填项')
    }

    return {
        role_id: payload.role_id,
    }
}

function validateSdkPermissionUserRoleBody(e) {
    const payload = parseBody(e)
    if (!payload.pb_id) {
        throw createAppError(400, 'pb_id 为必填项')
    }

    return {
        pb_id: payload.pb_id,
        usergroups_id: payload.usergroups_id || '',
    }
}

function validateSdkPermissionCollectionSaveBody(e) {
    const payload = parseBody(e)
    if (!payload.collection_name) {
        throw createAppError(400, 'collection_name 为必填项')
    }

    const rules = payload.rules && typeof payload.rules === 'object' ? payload.rules : {}

    return {
        collection_name: payload.collection_name,
        rules: {
            list: normalizeRuleConfig(rules.list),
            view: normalizeRuleConfig(rules.view),
            create: normalizeRuleConfig(rules.create),
            update: normalizeRuleConfig(rules.update),
            delete: normalizeRuleConfig(rules.delete),
        },
    }
}

function requireAuthOpenid(e) {
    if (!e.auth) {
        throw createAppError(401, '认证令牌无效或已过期')
    }

    if (e.auth.collection().name !== 'tbl_auth_users') {
        throw createAppError(401, '认证用户集合不正确')
    }

    const openid = e.auth.getString('openid')
    if (!openid) {
        throw createAppError(401, '当前认证用户缺少 openid')
    }

    return openid
}

function requireAuthUser(e) {
    const authHeader = e.request.header.get('Authorization') || ''
    const parts = authHeader.split(' ')

    if (parts.length !== 2 || parts[0] !== 'Bearer' || !parts[1]) {
        throw createAppError(401, '请求头缺少 Authorization')
    }

    if (!e.auth) {
        throw createAppError(401, '认证令牌无效或已过期')
    }

    if (e.auth.collection().name !== 'tbl_auth_users') {
        throw createAppError(401, '认证用户集合不正确')
    }

    const authOpenid = e.auth.getString('openid')
    if (!authOpenid) {
        throw createAppError(401, '当前认证用户缺少 openid')
    }

    return {
        openid: authOpenid,
        authRecord: e.auth,
    }
}

function duplicateGuard(e) {
    const key = String(e.realIP()) + ':' + String(e.request.url.pathname) + ':' + JSON.stringify(e.requestInfo().body || {})
    const now = Date.now()
    const lastTime = requestCache[key]

    if (lastTime && now - lastTime < WINDOW_MS) {
        throw createAppError(429, '请求过于频繁，请稍后重试')
    }

    requestCache[key] = now
}

module.exports = {
    parseBody,
    requireJson,
    validateLoginBody,
    validateProfileBody,
    validatePlatformRegisterBody,
    validatePlatformLoginBody,
    validateSystemRefreshBody,
    requireManagePlatformUser,
    validateDictionaryListBody,
    validateDictionaryDetailBody,
    validateDictionaryMutationBody,
    validateDictionaryDeleteBody,
    validateAttachmentListBody,
    validateAttachmentDetailBody,
    validateAttachmentDeleteBody,
    validateAttachmentUploadBody,
    validateDocumentListBody,
    validateDocumentDetailBody,
    validateDocumentMutationBody,
    validateDocumentDeleteBody,
    validateProductListBody,
    validateProductDetailBody,
    validateProductMutationBody,
    validateProductDeleteBody,
    validateSchemeTemplateListBody,
    validateSchemeTemplateDetailBody,
    validateSchemeTemplateMutationBody,
    validateSchemeTemplateDeleteBody,
    validateSchemeListBody,
    validateSchemeDetailBody,
    validateSchemeMutationBody,
    validateSchemeDeleteBody,
    validateCartListBody,
    validateCartDetailBody,
    validateCartMutationBody,
    validateCartDeleteBody,
    validateOrderListBody,
    validateOrderDetailBody,
    validateOrderMutationBody,
    validateOrderDeleteBody,
    validateCartOrderManageListBody,
    validateCartOrderManageUserUpdateBody,
    validateDocumentHistoryListBody,
    validateSdkPermissionContextBody,
    validateSdkPermissionRoleBody,
    validateSdkPermissionRoleDeleteBody,
    validateSdkPermissionUserRoleBody,
    validateSdkPermissionCollectionSaveBody,
    requireAuthOpenid,
    requireAuthUser,
    duplicateGuard,
}
