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

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

        const deployment_changes = await db.deployment_changes.create(
            {
                id: data.id || undefined,
        
        service_name: data.service_name
        ||
        null
            ,
            
        git_ref: data.git_ref
        ||
        null
            ,
            
        change_type: data.change_type
        ||
        null
            ,
            
        rollout_stage: data.rollout_stage
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        diff_summary: data.diff_summary
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await deployment_changes.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return deployment_changes;
    }
    

    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 deployment_changesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                service_name: item.service_name
            ||
            null
            ,
            
                git_ref: item.git_ref
            ||
            null
            ,
            
                change_type: item.change_type
            ||
            null
            ,
            
                rollout_stage: item.rollout_stage
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
                diff_summary: item.diff_summary
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return deployment_changes;
    }

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


        

        const updatePayload = {};
        
        if (data.service_name !== undefined) updatePayload.service_name = data.service_name;
        
        
        if (data.git_ref !== undefined) updatePayload.git_ref = data.git_ref;
        
        
        if (data.change_type !== undefined) updatePayload.change_type = data.change_type;
        
        
        if (data.rollout_stage !== undefined) updatePayload.rollout_stage = data.rollout_stage;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.diff_summary !== undefined) updatePayload.diff_summary = data.diff_summary;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return deployment_changes;
    }

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

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

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


        return deployment_changes;
    }

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

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

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

        await deployment_changes.destroy({
            transaction
        });

        return deployment_changes;
    }

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

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

        if (!deployment_changes) {
            return deployment_changes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organizations = await deployment_changes.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.service_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'deployment_changes',
                        'service_name',
                        filter.service_name,
                    ),
                };
            }
            
            if (filter.git_ref) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'deployment_changes',
                        'git_ref',
                        filter.git_ref,
                    ),
                };
            }
            
            if (filter.diff_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'deployment_changes',
                        'diff_summary',
                        filter.diff_summary,
                    ),
                };
            }
            

            
            

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

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

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

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

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

            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.rollout_stage) {
                where = {
                    ...where,
                rollout_stage: filter.rollout_stage,
            };
            }
            


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

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

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

    
};

