
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_itemsDBApi {
    

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

        const feedback_items = await db.feedback_items.create(
            {
                id: data.id || undefined,
        
        rating: data.rating
        ||
        null
            ,
            
        feedback_type: data.feedback_type
        ||
        null
            ,
            
        feedback_title: data.feedback_title
        ||
        null
            ,
            
        feedback_message: data.feedback_message
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await feedback_items.setSubmitted_by( data.submitted_by || null, {
            transaction,
        });
        
        await feedback_items.setSchool( data.school || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.feedback_items.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: feedback_items.id,
            },
            data.attachments,
            options,
        );
        

        return feedback_items;
    }
    

    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_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                rating: item.rating
            ||
            null
            ,
            
                feedback_type: item.feedback_type
            ||
            null
            ,
            
                feedback_title: item.feedback_title
            ||
            null
            ,
            
                feedback_message: item.feedback_message
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < feedback_items.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.feedback_items.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: feedback_items[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        return feedback_items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.rating !== undefined) updatePayload.rating = data.rating;
        
        
        if (data.feedback_type !== undefined) updatePayload.feedback_type = data.feedback_type;
        
        
        if (data.feedback_title !== undefined) updatePayload.feedback_title = data.feedback_title;
        
        
        if (data.feedback_message !== undefined) updatePayload.feedback_message = data.feedback_message;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.submitted_by !== undefined) {
            await feedback_items.setSubmitted_by(
              
              data.submitted_by,
              
              { transaction }
            );
        }
        
        if (data.school !== undefined) {
            await feedback_items.setSchool(
              
              data.school,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.feedback_items.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: feedback_items.id,
            },
            data.attachments,
            options,
        );
        

        return feedback_items;
    }

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

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

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


        return feedback_items;
    }

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

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

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

        await feedback_items.destroy({
            transaction
        });

        return feedback_items;
    }

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

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

        if (!feedback_items) {
            return feedback_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.submitted_by = await feedback_items.getSubmitted_by({
            transaction
        });
        
        
        output.school = await feedback_items.getSchool({
            transaction
        });
        
        
        output.attachments = await feedback_items.getAttachments({
            transaction
        });
        
        

        return output;
    }

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

        
        const user = (options && options.currentUser) || null;
        const userSchools = (user && user.schools?.id) || null;
        

        
        if (userSchools) {
            if (options?.currentUser?.schoolsId) {
                where.schoolsId = options.currentUser.schoolsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

      {
        model: db.schools,
        as: 'school',
        
      },



      {
        model: db.file,
        as: 'attachments',
      },

    ];

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

            
            if (filter.feedback_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'feedback_items',
                        'feedback_title',
                        filter.feedback_title,
                    ),
                };
            }
            
            if (filter.feedback_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'feedback_items',
                        'feedback_message',
                        filter.feedback_message,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    rating: {
                    ...where.rating,
                            [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.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      
      if (filter.school) {
        const listItems = filter.school.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          schoolId: {[Op.or]: listItems}
        };
      }
      



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

        
        if (globalAccess) {
            delete where.schoolsId;
        }
        

        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_items.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

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

    
};

