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

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

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

        
        await matrix_rows.setTest_matrix( data.test_matrix || null, {
            transaction,
        });
        
        await matrix_rows.setTest_item( data.test_item || null, {
            transaction,
        });
        
        await matrix_rows.setSkill( data.skill || null, {
            transaction,
        });
        

        

        

        return matrix_rows;
    }
    

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

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

        // For each item created, replace relation files
        

        return matrix_rows;
    }

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

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


        

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

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

        
        
        if (data.test_matrix !== undefined) {
            await matrix_rows.setTest_matrix(
              
              data.test_matrix,
              
              { transaction }
            );
        }
        
        if (data.test_item !== undefined) {
            await matrix_rows.setTest_item(
              
              data.test_item,
              
              { transaction }
            );
        }
        
        if (data.skill !== undefined) {
            await matrix_rows.setSkill(
              
              data.skill,
              
              { transaction }
            );
        }
        

        
        

        

        return matrix_rows;
    }

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

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

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


        return matrix_rows;
    }

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

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

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

        await matrix_rows.destroy({
            transaction
        });

        return matrix_rows;
    }

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

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

        if (!matrix_rows) {
            return matrix_rows;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.test_matrix = await matrix_rows.getTest_matrix({
            transaction
        });
        
        
        output.test_item = await matrix_rows.getTest_item({
            transaction
        });
        
        
        output.skill = await matrix_rows.getSkill({
            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_matrices,
        as: 'test_matrix',
        
        where: filter.test_matrix ? {
          [Op.or]: [
            { id: { [Op.in]: filter.test_matrix.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.test_matrix.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

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

            
            

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

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

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

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

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

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

    
};

