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

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

        const calendar_accounts = await db.calendar_accounts.create(
            {
                id: data.id || undefined,
        
        provider_account_email: data.provider_account_email
        ||
        null
            ,
            
        access_token_encrypted: data.access_token_encrypted
        ||
        null
            ,
            
        refresh_token_encrypted: data.refresh_token_encrypted
        ||
        null
            ,
            
        token_expires_at: data.token_expires_at
        ||
        null
            ,
            
        sync_status: data.sync_status
        ||
        null
            ,
            
        last_synced_at: data.last_synced_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await calendar_accounts.setTenant( data.tenant || null, {
            transaction,
        });
        
        await calendar_accounts.setUser( data.user || null, {
            transaction,
        });
        
        await calendar_accounts.setIntegration( data.integration || null, {
            transaction,
        });
        
        await calendar_accounts.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return calendar_accounts;
    }
    

    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 calendar_accountsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                provider_account_email: item.provider_account_email
            ||
            null
            ,
            
                access_token_encrypted: item.access_token_encrypted
            ||
            null
            ,
            
                refresh_token_encrypted: item.refresh_token_encrypted
            ||
            null
            ,
            
                token_expires_at: item.token_expires_at
            ||
            null
            ,
            
                sync_status: item.sync_status
            ||
            null
            ,
            
                last_synced_at: item.last_synced_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return calendar_accounts;
    }

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


        

        const updatePayload = {};
        
        if (data.provider_account_email !== undefined) updatePayload.provider_account_email = data.provider_account_email;
        
        
        if (data.access_token_encrypted !== undefined) updatePayload.access_token_encrypted = data.access_token_encrypted;
        
        
        if (data.refresh_token_encrypted !== undefined) updatePayload.refresh_token_encrypted = data.refresh_token_encrypted;
        
        
        if (data.token_expires_at !== undefined) updatePayload.token_expires_at = data.token_expires_at;
        
        
        if (data.sync_status !== undefined) updatePayload.sync_status = data.sync_status;
        
        
        if (data.last_synced_at !== undefined) updatePayload.last_synced_at = data.last_synced_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await calendar_accounts.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await calendar_accounts.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.integration !== undefined) {
            await calendar_accounts.setIntegration(
              
              data.integration,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await calendar_accounts.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return calendar_accounts;
    }

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

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

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


        return calendar_accounts;
    }

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

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

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

        await calendar_accounts.destroy({
            transaction
        });

        return calendar_accounts;
    }

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

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

        if (!calendar_accounts) {
            return calendar_accounts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.calendar_events_calendar_account = await calendar_accounts.getCalendar_events_calendar_account({
            transaction
        });
        
        
        
        
        output.tenant = await calendar_accounts.getTenant({
            transaction
        });
        
        
        output.user = await calendar_accounts.getUser({
            transaction
        });
        
        
        output.integration = await calendar_accounts.getIntegration({
            transaction
        });
        
        
        output.organizations = await calendar_accounts.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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.tenant.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.integrations,
        as: 'integration',
        
        where: filter.integration ? {
          [Op.or]: [
            { id: { [Op.in]: filter.integration.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.integration.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.provider_account_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'calendar_accounts',
                        'provider_account_email',
                        filter.provider_account_email,
                    ),
                };
            }
            
            if (filter.access_token_encrypted) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'calendar_accounts',
                        'access_token_encrypted',
                        filter.access_token_encrypted,
                    ),
                };
            }
            
            if (filter.refresh_token_encrypted) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'calendar_accounts',
                        'refresh_token_encrypted',
                        filter.refresh_token_encrypted,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.sync_status) {
                where = {
                    ...where,
                sync_status: filter.sync_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.calendar_accounts.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(
                        'calendar_accounts',
                        'provider_account_email',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

