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

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

        const code_patches = await db.code_patches.create(
            {
                id: data.id || undefined,
        
        file_path: data.file_path
        ||
        null
            ,
            
        change_type: data.change_type
        ||
        null
            ,
            
        diff_text: data.diff_text
        ||
        null
            ,
            
        applied_successfully: data.applied_successfully
        ||
        false
        
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await code_patches.setChange_set( data.change_set || null, {
            transaction,
        });
        
        await code_patches.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return code_patches;
    }
    

    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 code_patchesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                file_path: item.file_path
            ||
            null
            ,
            
                change_type: item.change_type
            ||
            null
            ,
            
                diff_text: item.diff_text
            ||
            null
            ,
            
                applied_successfully: item.applied_successfully
            ||
            false
        
            ,
            
                error_message: item.error_message
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return code_patches;
    }

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


        

        const updatePayload = {};
        
        if (data.file_path !== undefined) updatePayload.file_path = data.file_path;
        
        
        if (data.change_type !== undefined) updatePayload.change_type = data.change_type;
        
        
        if (data.diff_text !== undefined) updatePayload.diff_text = data.diff_text;
        
        
        if (data.applied_successfully !== undefined) updatePayload.applied_successfully = data.applied_successfully;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.change_set !== undefined) {
            await code_patches.setChange_set(
              
              data.change_set,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await code_patches.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return code_patches;
    }

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

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

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


        return code_patches;
    }

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

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

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

        await code_patches.destroy({
            transaction
        });

        return code_patches;
    }

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

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

        if (!code_patches) {
            return code_patches;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.change_set = await code_patches.getChange_set({
            transaction
        });
        
        
        output.organizations = await code_patches.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.code_change_sets,
        as: 'change_set',
        
        where: filter.change_set ? {
          [Op.or]: [
            { id: { [Op.in]: filter.change_set.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.change_set.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.file_path) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'code_patches',
                        'file_path',
                        filter.file_path,
                    ),
                };
            }
            
            if (filter.diff_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'code_patches',
                        'diff_text',
                        filter.diff_text,
                    ),
                };
            }
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'code_patches',
                        'error_message',
                        filter.error_message,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.change_type) {
                where = {
                    ...where,
                change_type: filter.change_type,
            };
            }
            
            if (filter.applied_successfully) {
                where = {
                    ...where,
                applied_successfully: filter.applied_successfully,
            };
            }
            


      

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

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

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

    
};

