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

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

        const surveys = await db.surveys.create(
            {
                id: data.id || undefined,
        
        survey_name: data.survey_name
        ||
        null
            ,
            
        survey_type: data.survey_type
        ||
        null
            ,
            
        introduction_text: data.introduction_text
        ||
        null
            ,
            
        is_anonymous: data.is_anonymous
        ||
        false
        
            ,
            
        status: data.status
        ||
        null
            ,
            
        opens_at: data.opens_at
        ||
        null
            ,
            
        closes_at: data.closes_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await surveys.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        

        

        

        return surveys;
    }
    

    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 surveysData = data.map((item, index) => ({
                id: item.id || undefined,
                
                survey_name: item.survey_name
            ||
            null
            ,
            
                survey_type: item.survey_type
            ||
            null
            ,
            
                introduction_text: item.introduction_text
            ||
            null
            ,
            
                is_anonymous: item.is_anonymous
            ||
            false
        
            ,
            
                status: item.status
            ||
            null
            ,
            
                opens_at: item.opens_at
            ||
            null
            ,
            
                closes_at: item.closes_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return surveys;
    }

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


        

        const updatePayload = {};
        
        if (data.survey_name !== undefined) updatePayload.survey_name = data.survey_name;
        
        
        if (data.survey_type !== undefined) updatePayload.survey_type = data.survey_type;
        
        
        if (data.introduction_text !== undefined) updatePayload.introduction_text = data.introduction_text;
        
        
        if (data.is_anonymous !== undefined) updatePayload.is_anonymous = data.is_anonymous;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.opens_at !== undefined) updatePayload.opens_at = data.opens_at;
        
        
        if (data.closes_at !== undefined) updatePayload.closes_at = data.closes_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await surveys.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        

        
        

        

        return surveys;
    }

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

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

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


        return surveys;
    }

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

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

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

        await surveys.destroy({
            transaction
        });

        return surveys;
    }

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

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

        if (!surveys) {
            return surveys;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.survey_questions_survey = await surveys.getSurvey_questions_survey({
            transaction
        });
        
        
        output.survey_responses_survey = await surveys.getSurvey_responses_survey({
            transaction
        });
        
        
        
        
        
        
        output.organization = await surveys.getOrganization({
            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.organizations,
        as: 'organization',
        
      },



    ];

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

            
            if (filter.survey_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'surveys',
                        'survey_name',
                        filter.survey_name,
                    ),
                };
            }
            
            if (filter.introduction_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'surveys',
                        'introduction_text',
                        filter.introduction_text,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.survey_type) {
                where = {
                    ...where,
                survey_type: filter.survey_type,
            };
            }
            
            if (filter.is_anonymous) {
                where = {
                    ...where,
                is_anonymous: filter.is_anonymous,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


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

        where = {
          ...where,
          organizationId: {[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.surveys.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(
                        'surveys',
                        'survey_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

