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

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

        const faq_articles = await db.faq_articles.create(
            {
                id: data.id || undefined,
        
        question: data.question
        ||
        null
            ,
            
        answer: data.answer
        ||
        null
            ,
            
        category: data.category
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        sort_order: data.sort_order
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await faq_articles.setStore( data.store || null, {
            transaction,
        });
        
        await faq_articles.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return faq_articles;
    }
    

    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 faq_articlesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                question: item.question
            ||
            null
            ,
            
                answer: item.answer
            ||
            null
            ,
            
                category: item.category
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                sort_order: item.sort_order
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return faq_articles;
    }

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


        

        const updatePayload = {};
        
        if (data.question !== undefined) updatePayload.question = data.question;
        
        
        if (data.answer !== undefined) updatePayload.answer = data.answer;
        
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.store !== undefined) {
            await faq_articles.setStore(
              
              data.store,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await faq_articles.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return faq_articles;
    }

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

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

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


        return faq_articles;
    }

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

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

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

        await faq_articles.destroy({
            transaction
        });

        return faq_articles;
    }

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

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

        if (!faq_articles) {
            return faq_articles;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.store = await faq_articles.getStore({
            transaction
        });
        
        
        output.organizations = await faq_articles.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.stores,
        as: 'store',
        
        where: filter.store ? {
          [Op.or]: [
            { id: { [Op.in]: filter.store.split('|').map(term => Utils.uuid(term)) } },
            {
              store_name: {
                [Op.or]: filter.store.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.question) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'faq_articles',
                        'question',
                        filter.question,
                    ),
                };
            }
            
            if (filter.answer) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'faq_articles',
                        'answer',
                        filter.answer,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

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

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

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

    
};

