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 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 USER_LEVEL_DICT_NAME = '数据-会员等级'

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

function buildPocketBaseRecordId(raw) {
    const normalized = normalizeText(raw).toLowerCase()
    if (/^[a-z0-9]{15}$/.test(normalized)) {
        return normalized
    }

    const fallback = String($security.randomString(15) || '').toLowerCase().replace(/[^a-z0-9]/g, 'a')
    if (fallback.length >= 15) {
        return fallback.slice(0, 15)
    }

    return (fallback + 'aaaaaaaaaaaaaaa').slice(0, 15)
}

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

function fetchAllRecordsByFilter(collectionName, filter, sort, params) {
    const batchSize = 200
    const result = []
    let offset = 0

    while (true) {
        const batch = $app.findRecordsByFilter(
            collectionName,
            filter || '',
            sort || '',
            batchSize,
            offset,
            params || {}
        )

        if (!batch.length) {
            break
        }

        for (let i = 0; i < batch.length; i += 1) {
            result.push(batch[i])
        }

        if (batch.length < batchSize) {
            break
        }

        offset += batch.length
    }

    return result
}

function normalizeOptionalNumberValue(value, fieldName) {
    if (value === '' || value === null || typeof value === 'undefined') {
        return null
    }

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

    return num
}

function normalizeSortValue(value) {
    if (value === '' || value === null || typeof value === 'undefined') {
        return 0
    }

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

    return Math.floor(num)
}

function normalizePipeValues(value) {
    if (Array.isArray(value)) {
        return value
            .map(function (item) {
                return normalizeText(item)
            })
            .filter(function (item) {
                return !!item
            })
    }

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

function joinUniquePipeValues(value) {
    const source = Array.isArray(value) ? value : normalizePipeValues(value)
    const result = []

    for (let i = 0; i < source.length; i += 1) {
        const current = normalizeText(source[i])
        if (!current || result.indexOf(current) !== -1) {
            continue
        }
        result.push(current)
    }

    return result.join('|')
}

function normalizeRequiredCategory(value) {
    const values = normalizePipeValues(value)
    if (!values.length) {
        throw createAppError(400, 'prod_list_category 为必填项')
    }
    return values[0]
}

function normalizePositiveSort(rawSort, fieldName, 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, fieldName + ' 必须为正整数')
    }

    return num
}

function normalizePositiveSortForOutput(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) {
        return fallbackSort
    }

    return num
}

function sortParameterRows(rows) {
    return rows
        .slice()
        .sort(function (a, b) {
            const sortDiff = Number(a.sort || 0) - Number(b.sort || 0)
            if (sortDiff !== 0) {
                return sortDiff
            }

            return Number(a.__inputIndex || 0) - Number(b.__inputIndex || 0)
        })
        .map(function (item) {
            return {
                name: item.name,
                value: item.value,
                sort: Number(item.sort || 0),
            }
        })
}

function safeObjectKeys(source) {
    if (!source || typeof source !== 'object') {
        return []
    }

    try {
        return Object.keys(source)
    } catch (_error) {
        return []
    }
}

function buildCategoryRankMap(records) {
    const grouped = {}
    for (let i = 0; i < records.length; i += 1) {
        const category = normalizeText(records[i].prod_list_category)
        if (!category) {
            continue
        }
        if (!grouped[category]) {
            grouped[category] = []
        }
        grouped[category].push(records[i])
    }

    const rankMap = {}
    const categories = Object.keys(grouped)
    for (let i = 0; i < categories.length; i += 1) {
        const category = categories[i]
        const items = grouped[category]
        items.sort(function (a, b) {
            const sortDiff = Number(a.prod_list_sort || 0) - Number(b.prod_list_sort || 0)
            if (sortDiff !== 0) {
                return sortDiff
            }

            const updateDiff = String(b.updated || '').localeCompare(String(a.updated || ''))
            if (updateDiff !== 0) {
                return updateDiff
            }

            return String(a.prod_list_id || '').localeCompare(String(b.prod_list_id || ''))
        })

        for (let j = 0; j < items.length; j += 1) {
            rankMap[items[j].prod_list_id] = j + 1
        }
    }

    return rankMap
}

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

    const result = []
    const indexByName = {}

    function upsert(nameValue, rawValue, rawSort, fallbackSort, inputIndex) {
        const name = normalizeText(nameValue)
        if (!name) {
            return
        }

        const normalizedValue = rawValue === null || typeof rawValue === 'undefined' ? '' : String(rawValue)
        const normalizedSort = normalizePositiveSort(rawSort, 'prod_list_parameters.sort', 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,
            __inputIndex: inputIndex,
        })
    }

    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, i + 1, i + 1)
        }
        return sortParameterRows(result)
    }

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

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

    return sortParameterRows(result)
}

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

    function pushOrUpdate(targetRows, indexByName, nameValue, rawValue, rawSort, fallbackSort, inputIndex) {
        const name = normalizeText(nameValue)
        if (!name) {
            return
        }

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

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

    let source = value
    if (typeof source === 'string') {
        try {
            source = JSON.parse(source)
            if (source === null) {
                return []
            }
        } catch (_error) {
            const raw = normalizeText(source)
            if (raw.indexOf('map[') === 0 && raw.endsWith(']')) {
                const body = raw.slice(4, -1).trim()
                if (!body) {
                    return []
                }
                const result = []
                const indexByName = {}
                const pairs = body.split(/\s+/)
                for (let i = 0; i < pairs.length; i += 1) {
                    const pair = pairs[i]
                    const separatorIndex = pair.indexOf(':')
                    if (separatorIndex <= 0) {
                        continue
                    }
                    const key = normalizeText(pair.slice(0, separatorIndex))
                    if (!key) {
                        continue
                    }
                    const val = pair.slice(separatorIndex + 1)
                    pushOrUpdate(result, indexByName, key, val, '', i + 1, i + 1)
                }
                return sortParameterRows(result)
            }
            return []
        }
    }

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

    if (typeof source !== 'object') {
        return []
    }

    if (source === null) {
        return []
    }

    // Some PocketBase/Goja map-like values are not directly enumerable; roundtrip to plain object.
    try {
        source = JSON.parse(JSON.stringify(source))
    } catch (_error) {}

    if (source === null || typeof source !== 'object') {
        return []
    }

    const result = []
    const indexByName = {}
    const keys = safeObjectKeys(source)
    for (let i = 0; i < keys.length; i += 1) {
        pushOrUpdate(result, indexByName, keys[i], source[keys[i]], '', i + 1, i + 1)
    }

    return sortParameterRows(result)
}

function getVipLevelValueMap() {
    let items = []
    try {
        items = dictionaryService.getDictionaryItemsByName(USER_LEVEL_DICT_NAME)
    } catch (_error) {
        items = []
    }
    const result = {}

    for (let i = 0; i < items.length; i += 1) {
        const key = normalizeText(items[i].enum)
        if (!key) {
            continue
        }
        result[key] = {
            value: key,
            label: String(items[i].description || ''),
        }
    }

    return result
}

function normalizeVipPriceRows(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 levelMap = getVipLevelValueMap()
    const result = []
    const duplicatedLevelMap = {}

    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 = normalizeText(item.viplevel)
        if (!viplevel) {
            throw createAppError(400, 'prod_list_vip_price 第 ' + (i + 1) + ' 项 viplevel 为必填项')
        }
        if (!levelMap[viplevel]) {
            throw createAppError(400, 'prod_list_vip_price 第 ' + (i + 1) + ' 项 viplevel 不在“数据-会员等级”字典中：' + viplevel)
        }

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

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

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

    return result
}

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

    let source = value
    if (typeof source === 'string') {
        try {
            source = JSON.parse(source)
        } catch (_error) {
            return []
        }
    }

    if (!Array.isArray(source)) {
        return []
    }

    const levelMap = getVipLevelValueMap()
    const result = []
    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 = normalizeText(item.viplevel)
        const price = Number(item.price)
        if (!viplevel || !Number.isFinite(price)) {
            continue
        }

        result.push({
            viplevel: viplevel,
            viplevel_name: levelMap[viplevel] ? levelMap[viplevel].label : '',
            price: price,
        })
    }

    return result
}

function normalizeAttachmentIdList(value) {
    const result = []
    const items = normalizePipeValues(value)

    for (let i = 0; i < items.length; i += 1) {
        if (result.indexOf(items[i]) === -1) {
            result.push(items[i])
        }
    }

    return result
}

function ensureAttachmentExists(attachmentId, fieldName) {
    const values = normalizeAttachmentIdList(attachmentId)
    if (!values.length) {
        return
    }

    for (let i = 0; i < values.length; i += 1) {
        try {
            documentService.getAttachmentDetail(values[i])
        } catch (_err) {
            throw createAppError(400, fieldName + ' 对应附件不存在：' + values[i])
        }
    }
}

function findProductRecordByBusinessId(productId) {
    const records = $app.findRecordsByFilter('tbl_product_list', 'prod_list_id = {:productId}', '', 1, 0, {
        productId: productId,
    })

    return records.length ? records[0] : null
}

function exportProductRecord(record, extra) {
    const iconIds = normalizeAttachmentIdList(record.getString('prod_list_icon'))
    const iconAttachments = []
    const iconUrls = []

    for (let i = 0; i < iconIds.length; i += 1) {
        try {
            const attachment = documentService.getAttachmentDetail(iconIds[i])
            iconAttachments.push(attachment)
            iconUrls.push(attachment.attachments_url || '')
        } catch (_error) {
            continue
        }
    }
    const firstIconAttachment = iconAttachments.length ? iconAttachments[0] : null

    const parametersText = normalizeText(record.getString('prod_list_parameters'))
    const parametersFromText = parametersText ? normalizeParametersForOutput(parametersText) : []
    const parametersRaw = record.get('prod_list_parameters')
    const parametersFromRaw = normalizeParametersForOutput(parametersRaw)
    const parameters = parametersFromText.length ? parametersFromText : parametersFromRaw
    const functionText = normalizeText(record.getString('prod_list_function'))
    const functionFromText = functionText ? normalizeParametersForOutput(functionText) : []
    const functionRaw = record.get('prod_list_function')
    const functionFromRaw = normalizeParametersForOutput(functionRaw)
    const functions = functionFromText.length ? functionFromText : functionFromRaw
    const vipPriceText = normalizeText(record.getString('prod_list_vip_price'))
    const vipPriceFromText = vipPriceText ? normalizeVipPriceRowsForOutput(vipPriceText) : []
    const vipPriceFromRaw = normalizeVipPriceRowsForOutput(record.get('prod_list_vip_price'))
    const vipPrice = vipPriceFromText.length ? vipPriceFromText : vipPriceFromRaw

    return {
        pb_id: record.id,
        prod_list_id: record.getString('prod_list_id'),
        prod_list_name: record.getString('prod_list_name'),
        prod_list_modelnumber: record.getString('prod_list_modelnumber'),
        prod_list_barcode: record.getString('prod_list_barcode'),
        prod_list_icon: iconIds.join('|'),
        prod_list_icon_ids: iconIds,
        prod_list_icon_attachments: iconAttachments,
        prod_list_icon_urls: iconUrls,
        prod_list_icon_attachment: firstIconAttachment,
        prod_list_icon_url: firstIconAttachment ? firstIconAttachment.attachments_url : '',
        prod_list_description: record.getString('prod_list_description'),
        prod_list_feature: record.getString('prod_list_feature'),
        prod_list_parameters: parameters,
        prod_list_function: functions,
        prod_list_plantype: record.getString('prod_list_plantype'),
        prod_list_category: record.getString('prod_list_category'),
        prod_list_sort: Number(record.get('prod_list_sort') || 0),
        prod_list_category_rank: extra && extra.categoryRank ? Number(extra.categoryRank) : 0,
        prod_list_comm_type: record.getString('prod_list_comm_type'),
        prod_list_series: record.getString('prod_list_series'),
        prod_list_power_supply: record.getString('prod_list_power_supply'),
        prod_list_tags: record.getString('prod_list_tags'),
        prod_list_basic_price: record.get('prod_list_basic_price'),
        prod_list_vip_price: vipPrice,
        prod_list_status: record.getString('prod_list_status'),
        prod_list_remark: record.getString('prod_list_remark'),
        created: String(record.created || ''),
        updated: String(record.updated || ''),
    }
}

function listProducts(payload) {
    try {
        const allRecords = fetchAllRecordsByFilter('tbl_product_list', '', '')
        const keyword = normalizeText(payload.keyword).toLowerCase()
        const status = normalizeText(payload.status)
        const category = normalizeText(payload.prod_list_category)
        const result = []

        const allItems = []
        for (let i = 0; i < allRecords.length; i += 1) {
            try {
                allItems.push(exportProductRecord(allRecords[i]))
            } catch (err) {
                logger.error('产品记录导出失败，已跳过', {
                    pb_id: allRecords[i] && allRecords[i].id ? allRecords[i].id : '',
                    prod_list_id: allRecords[i] ? allRecords[i].getString('prod_list_id') : '',
                    errMsg: (err && err.message) || '未知错误',
                })
            }
        }

        const rankMap = buildCategoryRankMap(allItems)

        for (let i = 0; i < allItems.length; i += 1) {
            const source = allItems[i]
            const item = Object.assign({}, source, {
                prod_list_category_rank: rankMap[source.prod_list_id] || 0,
            })
            const matchedKeyword = !keyword
                || item.prod_list_id.toLowerCase().indexOf(keyword) !== -1
                || item.prod_list_name.toLowerCase().indexOf(keyword) !== -1
                || item.prod_list_modelnumber.toLowerCase().indexOf(keyword) !== -1
                || item.prod_list_barcode.toLowerCase().indexOf(keyword) !== -1
                || item.prod_list_tags.toLowerCase().indexOf(keyword) !== -1
            const matchedStatus = !status || item.prod_list_status === status
            const matchedCategory = !category || item.prod_list_category === category

            if (matchedKeyword && matchedStatus && matchedCategory) {
                result.push(item)
            }
        }

        result.sort(function (a, b) {
            return String(b.updated || '').localeCompare(String(a.updated || ''))
        })

        return result
    } catch (err) {
        logger.error('产品列表构建失败，返回空列表兜底', {
            errMsg: (err && err.message) || '未知错误',
        })
        return []
    }
}

function getProductDetail(productId) {
    const record = findProductRecordByBusinessId(productId)
    if (!record) {
        throw createAppError(404, '未找到对应产品')
    }

    const allRecords = fetchAllRecordsByFilter('tbl_product_list', '', '')
    const allItems = []
    for (let i = 0; i < allRecords.length; i += 1) {
        allItems.push(exportProductRecord(allRecords[i]))
    }
    const rankMap = buildCategoryRankMap(allItems)

    return exportProductRecord(record, {
        categoryRank: rankMap[record.getString('prod_list_id')] || 0,
    })
}

function createProduct(_userOpenid, payload) {
    const targetProductId = normalizeText(payload.prod_list_id) || buildBusinessId('PROD')
    const duplicated = findProductRecordByBusinessId(targetProductId)
    if (duplicated) {
        throw createAppError(400, 'prod_list_id 已存在')
    }

    ensureAttachmentExists(payload.prod_list_icon, 'prod_list_icon')

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

    record.set('id', buildPocketBaseRecordId(payload && payload.id))
    record.set('prod_list_id', targetProductId)
    record.set('prod_list_name', normalizeText(payload.prod_list_name))
    record.set('prod_list_modelnumber', normalizeText(payload.prod_list_modelnumber))
    record.set('prod_list_barcode', normalizeText(payload.prod_list_barcode))
    record.set('prod_list_icon', joinUniquePipeValues(payload.prod_list_icon))
    record.set('prod_list_description', normalizeText(payload.prod_list_description))
    record.set('prod_list_feature', normalizeText(payload.prod_list_feature))
    record.set('prod_list_parameters', normalizeParameters(payload.prod_list_parameters))
    record.set('prod_list_function', normalizeParameters(payload.prod_list_function))
    record.set('prod_list_plantype', normalizeText(payload.prod_list_plantype))
    record.set('prod_list_category', normalizeRequiredCategory(payload.prod_list_category))
    record.set('prod_list_sort', normalizeSortValue(payload.prod_list_sort))
    record.set('prod_list_comm_type', normalizeText(payload.prod_list_comm_type))
    record.set('prod_list_series', normalizeText(payload.prod_list_series))
    record.set('prod_list_power_supply', normalizeText(payload.prod_list_power_supply))
    record.set('prod_list_tags', joinUniquePipeValues(payload.prod_list_tags))
    record.set('prod_list_status', normalizeText(payload.prod_list_status))
    record.set('prod_list_basic_price', normalizeOptionalNumberValue(payload.prod_list_basic_price, 'prod_list_basic_price'))
    record.set('prod_list_vip_price', normalizeVipPriceRows(payload.prod_list_vip_price))
    record.set('prod_list_remark', normalizeText(payload.prod_list_remark))

    try {
        $app.save(record)
    } catch (err) {
        throw createAppError(400, '新增产品失败', {
            originalMessage: (err && err.message) || '未知错误',
            originalData: (err && err.data) || {},
        })
    }

    logger.info('产品创建成功', {
        prod_list_id: record.getString('prod_list_id'),
    })

    const rankMap = buildCategoryRankMap(listProducts({}))
    return exportProductRecord(record, {
        categoryRank: rankMap[record.getString('prod_list_id')] || 0,
    })
}

function updateProduct(_userOpenid, payload) {
    const targetId = normalizeText(payload.prod_list_id)
    if (!targetId) {
        throw createAppError(400, 'prod_list_id 为必填项')
    }

    const record = findProductRecordByBusinessId(targetId)
    if (!record) {
        throw createAppError(404, '未找到待修改的产品')
    }

    ensureAttachmentExists(payload.prod_list_icon, 'prod_list_icon')

    record.set('prod_list_name', normalizeText(payload.prod_list_name))
    record.set('prod_list_modelnumber', normalizeText(payload.prod_list_modelnumber))
    record.set('prod_list_barcode', normalizeText(payload.prod_list_barcode))
    record.set('prod_list_icon', joinUniquePipeValues(payload.prod_list_icon))
    record.set('prod_list_description', normalizeText(payload.prod_list_description))
    record.set('prod_list_feature', normalizeText(payload.prod_list_feature))
    record.set('prod_list_parameters', normalizeParameters(payload.prod_list_parameters))
    record.set('prod_list_function', normalizeParameters(payload.prod_list_function))
    record.set('prod_list_plantype', normalizeText(payload.prod_list_plantype))
    record.set('prod_list_category', normalizeRequiredCategory(payload.prod_list_category))
    record.set('prod_list_sort', normalizeSortValue(payload.prod_list_sort))
    record.set('prod_list_comm_type', normalizeText(payload.prod_list_comm_type))
    record.set('prod_list_series', normalizeText(payload.prod_list_series))
    record.set('prod_list_power_supply', normalizeText(payload.prod_list_power_supply))
    record.set('prod_list_tags', joinUniquePipeValues(payload.prod_list_tags))
    record.set('prod_list_status', normalizeText(payload.prod_list_status))
    record.set('prod_list_basic_price', normalizeOptionalNumberValue(payload.prod_list_basic_price, 'prod_list_basic_price'))
    record.set('prod_list_vip_price', normalizeVipPriceRows(payload.prod_list_vip_price))
    record.set('prod_list_remark', normalizeText(payload.prod_list_remark))

    try {
        $app.save(record)
    } catch (err) {
        throw createAppError(400, '更新产品失败', {
            originalMessage: (err && err.message) || '未知错误',
            originalData: (err && err.data) || {},
        })
    }

    logger.info('产品更新成功', {
        prod_list_id: targetId,
    })

    const rankMap = buildCategoryRankMap(listProducts({}))
    return exportProductRecord(record, {
        categoryRank: rankMap[record.getString('prod_list_id')] || 0,
    })
}

function deleteProduct(_userOpenid, productId) {
    const targetId = normalizeText(productId)
    if (!targetId) {
        throw createAppError(400, 'prod_list_id 为必填项')
    }

    const record = findProductRecordByBusinessId(targetId)
    if (!record) {
        throw createAppError(404, '未找到待删除的产品')
    }

    try {
        $app.delete(record)
    } catch (err) {
        throw createAppError(400, '删除产品失败', {
            originalMessage: (err && err.message) || '未知错误',
            originalData: (err && err.data) || {},
        })
    }

    logger.info('产品删除成功', {
        prod_list_id: targetId,
    })

    return {
        prod_list_id: targetId,
    }
}

module.exports = {
    listProducts,
    getProductDetail,
    createProduct,
    updateProduct,
    deleteProduct,
}
