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

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

        const version_answer_orders = await db.version_answer_orders.create(
            {
                id: data.id || undefined,
        
        answer_order: data.answer_order
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await version_answer_orders.setTest_version( data.test_version || null, {
            transaction,
        });
        
        await version_answer_orders.setQuestion( data.question || null, {
            transaction,
        });
        

        

        

        return version_answer_orders;
    }
    

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

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

        // For each item created, replace relation files
        

        return version_answer_orders;
    }

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

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


        

        const updatePayload = {};
        
        if (data.answer_order !== undefined) updatePayload.answer_order = data.answer_order;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.test_version !== undefined) {
            await version_answer_orders.setTest_version(
              
              data.test_version,
              
              { transaction }
            );
        }
        
        if (data.question !== undefined) {
            await version_answer_orders.setQuestion(
              
              data.question,
              
              { transaction }
            );
        }
        

        
        

        

        return version_answer_orders;
    }

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

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

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


        return version_answer_orders;
    }

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

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

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

        await version_answer_orders.destroy({
            transaction
        });

        return version_answer_orders;
    }

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

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

        if (!version_answer_orders) {
            return version_answer_orders;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.test_version = await version_answer_orders.getTest_version({
            transaction
        });
        
        
        output.question = await version_answer_orders.getQuestion({
            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.test_versions,
        as: 'test_version',
        
        where: filter.test_version ? {
          [Op.or]: [
            { id: { [Op.in]: filter.test_version.split('|').map(term => Utils.uuid(term)) } },
            {
              version_label: {
                [Op.or]: filter.test_version.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

            

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

            


      

      



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

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

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

    
};

