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

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

        const shared_dashboard_posts = await db.shared_dashboard_posts.create(
            {
                id: data.id || undefined,
        
        post_type: data.post_type
        ||
        null
            ,
            
        title_text: data.title_text
        ||
        null
            ,
            
        content: data.content
        ||
        null
            ,
            
        posted_at: data.posted_at
        ||
        null
            ,
            
        visibility: data.visibility
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await shared_dashboard_posts.setPatient( data.patient || null, {
            transaction,
        });
        
        await shared_dashboard_posts.setAuthor_user( data.author_user || null, {
            transaction,
        });
        
        await shared_dashboard_posts.setAccounts( data.accounts || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.shared_dashboard_posts.getTableName(),
                belongsToColumn: 'photos',
                belongsToId: shared_dashboard_posts.id,
            },
            data.photos,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.shared_dashboard_posts.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: shared_dashboard_posts.id,
            },
            data.attachments,
            options,
        );
        

        return shared_dashboard_posts;
    }
    

    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 shared_dashboard_postsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                post_type: item.post_type
            ||
            null
            ,
            
                title_text: item.title_text
            ||
            null
            ,
            
                content: item.content
            ||
            null
            ,
            
                posted_at: item.posted_at
            ||
            null
            ,
            
                visibility: item.visibility
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < shared_dashboard_posts.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.shared_dashboard_posts.getTableName(),
                    belongsToColumn: 'photos',
                    belongsToId: shared_dashboard_posts[i].id,
                },
                data[i].photos,
                options,
            );
        }
        
        for (let i = 0; i < shared_dashboard_posts.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.shared_dashboard_posts.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: shared_dashboard_posts[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        return shared_dashboard_posts;
    }

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


        

        const updatePayload = {};
        
        if (data.post_type !== undefined) updatePayload.post_type = data.post_type;
        
        
        if (data.title_text !== undefined) updatePayload.title_text = data.title_text;
        
        
        if (data.content !== undefined) updatePayload.content = data.content;
        
        
        if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
        
        
        if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await shared_dashboard_posts.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.author_user !== undefined) {
            await shared_dashboard_posts.setAuthor_user(
              
              data.author_user,
              
              { transaction }
            );
        }
        
        if (data.accounts !== undefined) {
            await shared_dashboard_posts.setAccounts(
              
              data.accounts,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.shared_dashboard_posts.getTableName(),
                belongsToColumn: 'photos',
                belongsToId: shared_dashboard_posts.id,
            },
            data.photos,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.shared_dashboard_posts.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: shared_dashboard_posts.id,
            },
            data.attachments,
            options,
        );
        

        return shared_dashboard_posts;
    }

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

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

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


        return shared_dashboard_posts;
    }

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

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

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

        await shared_dashboard_posts.destroy({
            transaction
        });

        return shared_dashboard_posts;
    }

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

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

        if (!shared_dashboard_posts) {
            return shared_dashboard_posts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await shared_dashboard_posts.getPatient({
            transaction
        });
        
        
        output.author_user = await shared_dashboard_posts.getAuthor_user({
            transaction
        });
        
        
        output.photos = await shared_dashboard_posts.getPhotos({
            transaction
        });
        
        
        output.attachments = await shared_dashboard_posts.getAttachments({
            transaction
        });
        
        
        output.accounts = await shared_dashboard_posts.getAccounts({
            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 userAccounts = (user && user.accounts?.id) || null;
        

        
        if (userAccounts) {
            if (options?.currentUser?.accountsId) {
                where.accountsId = options.currentUser.accountsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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

      {
        model: db.accounts,
        as: 'accounts',
        
      },



      {
        model: db.file,
        as: 'photos',
      },

      {
        model: db.file,
        as: 'attachments',
      },

    ];

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

            
            if (filter.title_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'shared_dashboard_posts',
                        'title_text',
                        filter.title_text,
                    ),
                };
            }
            
            if (filter.content) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'shared_dashboard_posts',
                        'content',
                        filter.content,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.post_type) {
                where = {
                    ...where,
                post_type: filter.post_type,
            };
            }
            
            if (filter.visibility) {
                where = {
                    ...where,
                visibility: filter.visibility,
            };
            }
            


      

      

      
      if (filter.accounts) {
        const listItems = filter.accounts.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          accountsId: {[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.accountsId;
        }
        

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

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

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

    
};

