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

class filter_data_controllers {

    async findNonExistentVideoIDs(videoIds) {
        try {
            // 参数验证
            if (!videoIds) {
                throw new Error('videoIds parameter is required');
            }
            if (!Array.isArray(videoIds)) {
                throw new Error('videoIds must be an array');
            }
            if (videoIds.length === 0) {
                throw new Error('videoIds array cannot be empty');
            }
            if (!videoIds.every(id => typeof id === 'string' || typeof id === 'number')) {
                throw new Error('All video IDs must be strings or numbers');
            }
    
            // 限制最大处理数量为500
            const maxIds = videoIds.slice(0, 500);
    
            // 构建 IN 查询条件
            const placeholders = maxIds.map(() => '?').join(',');
            const sql = `SELECT video_id FROM ?? WHERE video_id IN (${placeholders})`;
            
            // 执行查询
            const existingRecords = await filter_data_model.query(sql, [filter_data_model.tableName, ...maxIds]);
    
            // 获取已存在的video_id集合
            const existingVideoIDs = new Set(
                existingRecords.map(record => record.video_id)
            );
    
            // 找出不存在的video_id
            const nonExistentVideoIDs = maxIds.filter(
                id => !existingVideoIDs.has(id)
            );
    
            return {
                success: true,
                data: {
                    total: maxIds.length,
                    existing: existingVideoIDs.size,
                    nonExistent: nonExistentVideoIDs.length,
                    nonExistentIds: nonExistentVideoIDs
                }
            };
    
        } catch (error) {
            console.error('Error in findNonExistentVideoIDs:', error);
            return {
                success: false,
                error: error.toString()  // 确保错误消息始终是字符串
            };
        }
    }
    /**
     * 获取过滤数据
     * @param {Object} params - 请求参数
     * @param {string} params.video_id - 视频ID
     * @returns {Promise<Object>} 过滤数据
     */
    async getFilterData(params) {
        try {
            // 参数验证
            if (!params?.video_id) {
                throw  'filter_data_controllers: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;
        }
    }

    async getFilterDataByBookIdAndLimit(params,limit=1) {
        try {
            // 参数验证
            if (params.book_id==undefined||params.book_id==null||params.status==undefined) {
                throw  'filter_data_controllers:book_id or status  is required';
            }

            const filterData = await filter_data_model.findDataByLimit({ book_id: params.book_id,status:params.status},limit);

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

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

            throw error;
        }
    }


    async getFilterDataByStatusAndLimit(params,limit=1,orderBy="") {
        try {
            // 参数验证
            if (params.status==undefined||params.status==null||params.tg_platform_id==undefined) {
                throw  'filter_data_controllers:status or tg_platform_id is required';
            }

            const status = params.status;
            const filterData = await filter_data_model.findDataByLimit({ status: status ,tg_platform_id:params.tg_platform_id},limit,orderBy);

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

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

            throw error;
        }
    }

    async getFilterDataByStatus(params) {
        try {
            // 参数验证
            if (undefined==params.status||null==params.status||params.tg_platform_id==undefined) {
                throw  'filter_data_controllers:status or tg_platform_id is required';
            }

            const status = params.status;
            const filterData = await filter_data_model.findOne({ status: status ,tg_platform_id:params.tg_platform_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']; // 替换为实际必要字段
            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?.id) {
                throw 'ID is required';
            }

            if (!tableData || Object.keys(tableData).length === 0) {
                throw 'No data to update';
            }
            // 检查数据是否存在
            // 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(
                params?.id,
                tableData
            );

            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;
        }
    }


    async updateFilterDataByIds(params, tableData) {
        try {
            // 参数验证
            if (!params?.ids || !Array.isArray(params.ids) || params.ids.length === 0) {
                throw new Error('ids must be a non-empty array');
            }
    
            if (!tableData || Object.keys(tableData).length === 0) {
                throw new Error('No data to update');
            }
    
            const ids = params.ids;
    
            // 构建批量更新SQL
            const updateFields = Object.entries(tableData)
                .map(([key, value]) => `${key} = ?`)
                .join(', ');
                
            const placeholders = ids.map(() => '?').join(',');
            
            const sql = `
                UPDATE filter_data 
                SET ${updateFields}
                WHERE id IN (${placeholders})
            `;
    
            // 构建参数数组：先是set的值，然后是where in的值
            const values = [
                ...Object.values(tableData),
                ...ids
            ];
    
            // 执行更新
            const result = await filter_data_model.query(sql, values);
    
            return {
                success: true,
                message: `Successfully updated ${result.affectedRows} records`,
                data: {
                    affectedRows: result.affectedRows
                }
            };
    
        } catch (error) {
            console.error('Error in updateFilterData:', error);
            throw error;
        }
    }
}

module.exports =  new filter_data_controllers();