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

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

        const offline_sync_batches = await db.offline_sync_batches.create(
            {
                id: data.id || undefined,
        
        created_at_local: data.created_at_local
        ||
        null
            ,
            
        synced_at: data.synced_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        items_count: data.items_count
        ||
        null
            ,
            
        payload_json: data.payload_json
        ||
        null
            ,
            
        error_details: data.error_details
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await offline_sync_batches.setUser( data.user || null, {
            transaction,
        });
        
        await offline_sync_batches.setProject( data.project || null, {
            transaction,
        });
        
        await offline_sync_batches.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return offline_sync_batches;
    }
    

    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 offline_sync_batchesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                created_at_local: item.created_at_local
            ||
            null
            ,
            
                synced_at: item.synced_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                items_count: item.items_count
            ||
            null
            ,
            
                payload_json: item.payload_json
            ||
            null
            ,
            
                error_details: item.error_details
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return offline_sync_batches;
    }

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


        

        const updatePayload = {};
        
        if (data.created_at_local !== undefined) updatePayload.created_at_local = data.created_at_local;
        
        
        if (data.synced_at !== undefined) updatePayload.synced_at = data.synced_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.items_count !== undefined) updatePayload.items_count = data.items_count;
        
        
        if (data.payload_json !== undefined) updatePayload.payload_json = data.payload_json;
        
        
        if (data.error_details !== undefined) updatePayload.error_details = data.error_details;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await offline_sync_batches.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.project !== undefined) {
            await offline_sync_batches.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await offline_sync_batches.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return offline_sync_batches;
    }

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

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

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


        return offline_sync_batches;
    }

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

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

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

        await offline_sync_batches.destroy({
            transaction
        });

        return offline_sync_batches;
    }

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

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

        if (!offline_sync_batches) {
            return offline_sync_batches;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await offline_sync_batches.getUser({
            transaction
        });
        
        
        output.project = await offline_sync_batches.getProject({
            transaction
        });
        
        
        output.organizations = await offline_sync_batches.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.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.projects,
        as: 'project',
        
        where: filter.project ? {
          [Op.or]: [
            { id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.project.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.payload_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'offline_sync_batches',
                        'payload_json',
                        filter.payload_json,
                    ),
                };
            }
            
            if (filter.error_details) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'offline_sync_batches',
                        'error_details',
                        filter.error_details,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    items_count: {
                    ...where.items_count,
                            [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.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.offline_sync_batches.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(
                        'offline_sync_batches',
                        'status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

