const filter_data_model =  require('../Model/filter_data_model');

class filter_data_controllers {
    /**
     * 获取过滤数据
     * @param {Object} params - 请求参数
     * @param {string} params.video_id - 视频ID
     * @returns {Promise<Object>} 过滤数据
     */
    async getFilterData(params) {
        try {
            // 参数验证
            if (!params?.video_id) {
                throw  'Video ID is required';
            }

            const video_id = params.video_id;
            const filterData = await filter_data_model.findOne({ video_id: video_id });

            if (!filterData) {
                return {
                    success: false,
                    data: null
                };
            }

            return {
                success: true,
                data: filterData
            };
        } catch (error) {

            throw error;
        }
    }

    /**
     * 创建过滤数据
     * @param {Object} tableData - 要创建的数据
     * @returns {Promise<Object>} 创建结果
     */
    async createFilterData(tableData) {
        try {
            // 数据验证
            if (!tableData || Object.keys(tableData).length === 0) {
                throw 'Invalid table data';
            }

            // 检查必要字段
            const requiredFields = ['video_id', 
                'video_link', 
                'title',
                'publish_time',
                'kepp_num','comment_num','like_num','shared_num','is_guajian','book_id','book_name','genre'
                ,'words','guajian_link','tg_platform_id','source']; // 替换为实际必要字段
            for (const field of requiredFields) {
                if (tableData[field]==null||tableData[field]==undefined) {
                    throw `Missing required field: ${field}`;
                }
            }

            // 添加创建时间戳
            // const dataToCreate = {
            //     ...tableData
            //     // created_at: new Date(),
            //     // updated_at: new Date()
            // };

            const id = await filter_data_model.createFilterData(tableData);


            return {
                success: true,
                data: { id }
            };
        } catch (error) {
            throw error;
        }
    }

    /**
     * 更新过滤数据
     * @param {Object} params - 请求参数
     * @param {string} params.id - 数据ID
     * @param {Object} tableData - 更新数据
     * @returns {Promise<Object>} 更新结果
     */
    async updateFilterData(params, tableData) {
        try {
            // 参数验证
            if (!params?.video_id) {
                throw 'ID is required';
            }

            if (!tableData || Object.keys(tableData).length === 0) {
                throw 'No data to update';
            }

            const video_id = params.video_id;

            // 检查数据是否存在
            const existingData = await filter_data_model.findOne({ video_id:video_id });
            if (!existingData) {
                throw 'Filter data not found';
            }

            // 添加更新时间戳
            // const dataToUpdtableDataate = {
            //     ...,
            // };

            // 使用乐观锁更新
            const affectedRows = await filter_data_model.updateFilterData(
                id,
                dataToUpdate,
                existingData.version // 假设使用版本控制
            );

            if (affectedRows === 0) {
                throw 'Data was modified by another process';
            }
            return {
                success: true,
                message: 'Filter data updated successfully'
            };
        } catch (error) {
            throw error;
        }
    }

    /**
     * 批量更新过滤数据
     * @param {Array} items - 要更新的数据项数组
     * @returns {Promise<Object>} 更新结果
     */
    async batchUpdateFilterData(items) {
        try {
            const results = await filter_data_model.transaction(async (connection) => {
                const updates = [];
                for (const item of items) {
                    const result = await connection.query(
                        'UPDATE filter_data SET ? WHERE id = ?',
                        [{ ...item, updated_at: new Date() }, item.id]
                    );
                    updates.push(result);
                }
                return updates;
            });

            return {
                success: true,
                data: results
            };
        } catch (error) {
            throw error;
        }
    }

    /**
     * 删除过滤数据
     * @param {string} id - 要删除的数据ID
     * @returns {Promise<Object>} 删除结果
     */
    async deleteFilterData(id) {
        try {
            if (!id) {
                throw 'ID is required';
            }

            const result = await filter_data_model.delete({ id });

            if (result.affectedRows === 0) {
                throw  'Filter data not found';
            }

            return {
                success: true,
                message: 'Filter data deleted successfully'
            };
        } catch (error) {
            throw error;
        }
    }
}

module.exports =  new filter_data_controllers();