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

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

        const survey_questions = await db.survey_questions.create(
            {
                id: data.id || undefined,
        
        question_type: data.question_type
        ||
        null
            ,
            
        prompt: data.prompt
        ||
        null
            ,
            
        sequence_order: data.sequence_order
        ||
        null
            ,
            
        is_required: data.is_required
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await survey_questions.setSurvey( data.survey || null, {
            transaction,
        });
        
        await survey_questions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return survey_questions;
    }
    

    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 survey_questionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                question_type: item.question_type
            ||
            null
            ,
            
                prompt: item.prompt
            ||
            null
            ,
            
                sequence_order: item.sequence_order
            ||
            null
            ,
            
                is_required: item.is_required
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return survey_questions;
    }

    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 survey_questions = await db.survey_questions.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.question_type !== undefined) updatePayload.question_type = data.question_type;
        
        
        if (data.prompt !== undefined) updatePayload.prompt = data.prompt;
        
        
        if (data.sequence_order !== undefined) updatePayload.sequence_order = data.sequence_order;
        
        
        if (data.is_required !== undefined) updatePayload.is_required = data.is_required;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.survey !== undefined) {
            await survey_questions.setSurvey(
              
              data.survey,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await survey_questions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return survey_questions;
    }

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

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

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


        return survey_questions;
    }

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

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

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

        await survey_questions.destroy({
            transaction
        });

        return survey_questions;
    }

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

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

        if (!survey_questions) {
            return survey_questions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.survey_response_items_survey_question = await survey_questions.getSurvey_response_items_survey_question({
            transaction
        });
        
        
        
        
        
        output.survey = await survey_questions.getSurvey({
            transaction
        });
        
        
        output.organizations = await survey_questions.getOrganizations({
            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 userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

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

            
            

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

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

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

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

            
            if (filter.question_type) {
                where = {
                    ...where,
                question_type: filter.question_type,
            };
            }
            
            if (filter.is_required) {
                where = {
                    ...where,
                is_required: filter.is_required,
            };
            }
            


      

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

        where = {
          ...where,
          organizationsId: {[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.organizationsId;
        }
        

        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.survey_questions.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(
                        'survey_questions',
                        'prompt',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

