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

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

        const sharing_permissions = await db.sharing_permissions.create(
            {
                id: data.id || undefined,
        
        data_category: data.data_category
        ||
        null
            ,
            
        access_level: data.access_level
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await sharing_permissions.setFamily_group( data.family_group || null, {
            transaction,
        });
        
        await sharing_permissions.setGranter_user( data.granter_user || null, {
            transaction,
        });
        
        await sharing_permissions.setGrantee_user( data.grantee_user || null, {
            transaction,
        });
        

        

        

        return sharing_permissions;
    }
    

    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 sharing_permissionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                data_category: item.data_category
            ||
            null
            ,
            
                access_level: item.access_level
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return sharing_permissions;
    }

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

        const sharing_permissions = await db.sharing_permissions.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.data_category !== undefined) updatePayload.data_category = data.data_category;
        
        
        if (data.access_level !== undefined) updatePayload.access_level = data.access_level;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.family_group !== undefined) {
            await sharing_permissions.setFamily_group(
              
              data.family_group,
              
              { transaction }
            );
        }
        
        if (data.granter_user !== undefined) {
            await sharing_permissions.setGranter_user(
              
              data.granter_user,
              
              { transaction }
            );
        }
        
        if (data.grantee_user !== undefined) {
            await sharing_permissions.setGrantee_user(
              
              data.grantee_user,
              
              { transaction }
            );
        }
        

        
        

        

        return sharing_permissions;
    }

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

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

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


        return sharing_permissions;
    }

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

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

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

        await sharing_permissions.destroy({
            transaction
        });

        return sharing_permissions;
    }

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

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

        if (!sharing_permissions) {
            return sharing_permissions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.family_group = await sharing_permissions.getFamily_group({
            transaction
        });
        
        
        output.granter_user = await sharing_permissions.getGranter_user({
            transaction
        });
        
        
        output.grantee_user = await sharing_permissions.getGrantee_user({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.family_groups,
        as: 'family_group',
        
        where: filter.family_group ? {
          [Op.or]: [
            { id: { [Op.in]: filter.family_group.split('|').map(term => Utils.uuid(term)) } },
            {
              group_name: {
                [Op.or]: filter.family_group.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'granter_user',
        
        where: filter.granter_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.granter_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.granter_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'grantee_user',
        
        where: filter.grantee_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.grantee_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.grantee_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

            
            

            

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

            
            if (filter.data_category) {
                where = {
                    ...where,
                data_category: filter.data_category,
            };
            }
            
            if (filter.access_level) {
                where = {
                    ...where,
                access_level: filter.access_level,
            };
            }
            


      

      

      



            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,
                        },
                    };
                }
            }
        }
        

        

        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.sharing_permissions.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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'sharing_permissions',
                        'data_category',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

