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

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

        const private_mailboxes = await db.private_mailboxes.create(
            {
                id: data.id || undefined,
        
        public_label: data.public_label
        ||
        null
            ,
            
        is_enabled: data.is_enabled
        ||
        false
        
            ,
            
        allow_attachments: data.allow_attachments
        ||
        false
        
            ,
            
        delivery_mode: data.delivery_mode
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await private_mailboxes.setOwner_creator( data.owner_creator || null, {
            transaction,
        });
        
        await private_mailboxes.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return private_mailboxes;
    }
    

    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 private_mailboxesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                public_label: item.public_label
            ||
            null
            ,
            
                is_enabled: item.is_enabled
            ||
            false
        
            ,
            
                allow_attachments: item.allow_attachments
            ||
            false
        
            ,
            
                delivery_mode: item.delivery_mode
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return private_mailboxes;
    }

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


        

        const updatePayload = {};
        
        if (data.public_label !== undefined) updatePayload.public_label = data.public_label;
        
        
        if (data.is_enabled !== undefined) updatePayload.is_enabled = data.is_enabled;
        
        
        if (data.allow_attachments !== undefined) updatePayload.allow_attachments = data.allow_attachments;
        
        
        if (data.delivery_mode !== undefined) updatePayload.delivery_mode = data.delivery_mode;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return private_mailboxes;
    }

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

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

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


        return private_mailboxes;
    }

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

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

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

        await private_mailboxes.destroy({
            transaction
        });

        return private_mailboxes;
    }

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

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

        if (!private_mailboxes) {
            return private_mailboxes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.messages_mailbox = await private_mailboxes.getMessages_mailbox({
            transaction
        });
        
        
        
        
        
        
        output.owner_creator = await private_mailboxes.getOwner_creator({
            transaction
        });
        
        
        output.organizations = await private_mailboxes.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.creator_profiles,
        as: 'owner_creator',
        
        where: filter.owner_creator ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner_creator.split('|').map(term => Utils.uuid(term)) } },
            {
              handle: {
                [Op.or]: filter.owner_creator.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.public_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'private_mailboxes',
                        'public_label',
                        filter.public_label,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.is_enabled) {
                where = {
                    ...where,
                is_enabled: filter.is_enabled,
            };
            }
            
            if (filter.allow_attachments) {
                where = {
                    ...where,
                allow_attachments: filter.allow_attachments,
            };
            }
            
            if (filter.delivery_mode) {
                where = {
                    ...where,
                delivery_mode: filter.delivery_mode,
            };
            }
            


      

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

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

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

    
};

