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

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

        const code_change_sets = await db.code_change_sets.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        created_at_time: data.created_at_time
        ||
        null
            ,
            
        applied_at: data.applied_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await code_change_sets.setWorkspace( data.workspace || null, {
            transaction,
        });
        
        await code_change_sets.setUser( data.user || null, {
            transaction,
        });
        
        await code_change_sets.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await code_change_sets.setPatch_files(data.patch_files || [], {
            transaction,
        });
        

        

        return code_change_sets;
    }
    

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

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

        // For each item created, replace relation files
        

        return code_change_sets;
    }

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.created_at_time !== undefined) updatePayload.created_at_time = data.created_at_time;
        
        
        if (data.applied_at !== undefined) updatePayload.applied_at = data.applied_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workspace !== undefined) {
            await code_change_sets.setWorkspace(
              
              data.workspace,
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await code_change_sets.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await code_change_sets.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.patch_files !== undefined) {
            await code_change_sets.setPatch_files(data.patch_files, { transaction });
        }
        

        

        return code_change_sets;
    }

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

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

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


        return code_change_sets;
    }

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

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

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

        await code_change_sets.destroy({
            transaction
        });

        return code_change_sets;
    }

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

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

        if (!code_change_sets) {
            return code_change_sets;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.code_patches_change_set = await code_change_sets.getCode_patches_change_set({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.workspace = await code_change_sets.getWorkspace({
            transaction
        });
        
        
        output.user = await code_change_sets.getUser({
            transaction
        });
        
        
        output.patch_files = await code_change_sets.getPatch_files({
            transaction
        });
        
        
        output.organizations = await code_change_sets.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.workspaces,
        as: 'workspace',
        
        where: filter.workspace ? {
          [Op.or]: [
            { id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },


      {
        model: db.code_patches,
        as: 'patch_files',
        required: false,
      },


    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'code_change_sets',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'code_change_sets',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            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.patch_files) {
        const searchTerms = filter.patch_files.split('|');

        include = [
          {
            model: db.code_patches,
            as: 'patch_files_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  file_path: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


            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_change_sets.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_change_sets',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

