
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Feedback_entriesDBApi {
    

    
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const feedback_entries = await db.feedback_entries.create(
            {
                id: data.id || undefined,
        
        feedback_type: data.feedback_type
        ||
        null
            ,
            
        score: data.score
        ||
        null
            ,
            
        comment: data.comment
        ||
        null
            ,
            
        source_surface: data.source_surface
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        needs_follow_up: data.needs_follow_up
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await feedback_entries.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return feedback_entries;
    }
    

    static async bulkImport(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        // Prepare data - wrapping individual data transformations in a map() method
        const feedback_entriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                feedback_type: item.feedback_type
            ||
            null
            ,
            
                score: item.score
            ||
            null
            ,
            
                comment: item.comment
            ||
            null
            ,
            
                source_surface: item.source_surface
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                needs_follow_up: item.needs_follow_up
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const feedback_entries = await db.feedback_entries.bulkCreate(feedback_entriesData, { transaction });

        // For each item created, replace relation files
        

        return feedback_entries;
    }

    static async update(id, data,  options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;
        

        const feedback_entries = await db.feedback_entries.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.feedback_type !== undefined) updatePayload.feedback_type = data.feedback_type;
        
        
        if (data.score !== undefined) updatePayload.score = data.score;
        
        
        if (data.comment !== undefined) updatePayload.comment = data.comment;
        
        
        if (data.source_surface !== undefined) updatePayload.source_surface = data.source_surface;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.needs_follow_up !== undefined) updatePayload.needs_follow_up = data.needs_follow_up;
        
        
        updatePayload.updatedById = currentUser.id;

        await feedback_entries.update(updatePayload, {transaction});

        
        
        if (data.user !== undefined) {
            await feedback_entries.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        

        return feedback_entries;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const feedback_entries = await db.feedback_entries.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

        await db.sequelize.transaction(async (transaction) => {
            for (const record of feedback_entries) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of feedback_entries) {
                await record.destroy({transaction});
            }
        });


        return feedback_entries;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const feedback_entries = await db.feedback_entries.findByPk(id, options);

        await feedback_entries.update({
            deletedBy: currentUser.id
        }, {
            transaction,
        });

        await feedback_entries.destroy({
            transaction
        });

        return feedback_entries;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;

        const feedback_entries = await db.feedback_entries.findOne(
            { where },
            { transaction },
        );

        if (!feedback_entries) {
            return feedback_entries;
        }

        const output = feedback_entries.get({plain: true});

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await feedback_entries.getUser({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

            
            if (filter.comment) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'feedback_entries',
                        'comment',
                        filter.comment,
                    ),
                };
            }
            

            
            

            
            if (filter.scoreRange) {
                const [start, end] = filter.scoreRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    score: {
                    ...where.score,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    score: {
                    ...where.score,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.submitted_atRange) {
                const [start, end] = filter.submitted_atRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    submitted_at: {
                    ...where.submitted_at,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    submitted_at: {
                    ...where.submitted_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.feedback_type) {
                where = {
                    ...where,
                feedback_type: filter.feedback_type,
            };
            }
            
            if (filter.source_surface) {
                where = {
                    ...where,
                source_surface: filter.source_surface,
            };
            }
            
            if (filter.needs_follow_up) {
                where = {
                    ...where,
                needs_follow_up: filter.needs_follow_up,
            };
            }
            


      



            if (filter.createdAtRange) {
                const [start, end] = filter.createdAtRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.gte]: start,
                        },
                    };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.lte]: end,
                        },
                    };
                }
            }
        }
        

        

        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options?.transaction,
            logging: console.log
        };

        if (!options?.countOnly) {
            queryOptions.limit = limit ? Number(limit) : undefined;
            queryOptions.offset = offset ? Number(offset) : undefined;
        }

        try {
            const { rows, count } = await db.feedback_entries.findAndCountAll(queryOptions);

            return {
                rows: options?.countOnly ? [] : rows,
                count: count
            };
        } catch (error) {
            console.error('Error executing query:', error);
            throw error;
        }
    }

    static async findAllAutocomplete(query, limit, offset, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'feedback_entries',
                        'feedback_type',
                        query,
                    ),
                ],
            };
        }

        const records = await db.feedback_entries.findAll({
            attributes: [ 'id', 'feedback_type' ],
            where,
            limit: limit ? Number(limit) : undefined,
            offset: offset ? Number(offset) : undefined,
            orderBy: [['feedback_type', 'ASC']],
        });

        return records.map((record) => ({
            id: record.id,
            label: record.feedback_type,
        }));
    }

    
};

