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

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

        const external_accounts = await db.external_accounts.create(
            {
                id: data.id || undefined,
        
        provider: data.provider
        ||
        null
            ,
            
        handle: data.handle
        ||
        null
            ,
            
        profile_url: data.profile_url
        ||
        null
            ,
            
        access_token_hint: data.access_token_hint
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        connected_at: data.connected_at
        ||
        null
            ,
            
        last_synced_at: data.last_synced_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return external_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 external_accountsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                provider: item.provider
            ||
            null
            ,
            
                handle: item.handle
            ||
            null
            ,
            
                profile_url: item.profile_url
            ||
            null
            ,
            
                access_token_hint: item.access_token_hint
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                connected_at: item.connected_at
            ||
            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 external_accounts = await db.external_accounts.bulkCreate(external_accountsData, { transaction });

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.provider !== undefined) updatePayload.provider = data.provider;
        
        
        if (data.handle !== undefined) updatePayload.handle = data.handle;
        
        
        if (data.profile_url !== undefined) updatePayload.profile_url = data.profile_url;
        
        
        if (data.access_token_hint !== undefined) updatePayload.access_token_hint = data.access_token_hint;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.connected_at !== undefined) updatePayload.connected_at = data.connected_at;
        
        
        if (data.last_synced_at !== undefined) updatePayload.last_synced_at = data.last_synced_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return external_accounts;
    }

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

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

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


        return external_accounts;
    }

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

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

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

        await external_accounts.destroy({
            transaction
        });

        return external_accounts;
    }

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

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

        if (!external_accounts) {
            return external_accounts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await external_accounts.getUser({
            transaction
        });
        
        
        output.organizations = await external_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.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',
        
      },



    ];

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

            
            if (filter.handle) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'external_accounts',
                        'handle',
                        filter.handle,
                    ),
                };
            }
            
            if (filter.profile_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'external_accounts',
                        'profile_url',
                        filter.profile_url,
                    ),
                };
            }
            
            if (filter.access_token_hint) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'external_accounts',
                        'access_token_hint',
                        filter.access_token_hint,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    connected_at: {
                    ...where.connected_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.provider) {
                where = {
                    ...where,
                provider: filter.provider,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      

      
      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.external_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(
                        'external_accounts',
                        'handle',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

