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

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

        const announcements = await db.announcements.create(
            {
                id: data.id || undefined,
        
        announcement_title: data.announcement_title
        ||
        null
            ,
            
        announcement_body: data.announcement_body
        ||
        null
            ,
            
        audience_type: data.audience_type
        ||
        null
            ,
            
        target_role: data.target_role
        ||
        null
            ,
            
        posted_at: data.posted_at
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        pinned: data.pinned
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await announcements.setSchool( data.school || null, {
            transaction,
        });
        
        await announcements.setClassroom( data.classroom || null, {
            transaction,
        });
        
        await announcements.setPosted_by( data.posted_by || null, {
            transaction,
        });
        

        

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

        return announcements;
    }
    

    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 announcementsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                announcement_title: item.announcement_title
            ||
            null
            ,
            
                announcement_body: item.announcement_body
            ||
            null
            ,
            
                audience_type: item.audience_type
            ||
            null
            ,
            
                target_role: item.target_role
            ||
            null
            ,
            
                posted_at: item.posted_at
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                pinned: item.pinned
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return announcements;
    }

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


        

        const updatePayload = {};
        
        if (data.announcement_title !== undefined) updatePayload.announcement_title = data.announcement_title;
        
        
        if (data.announcement_body !== undefined) updatePayload.announcement_body = data.announcement_body;
        
        
        if (data.audience_type !== undefined) updatePayload.audience_type = data.audience_type;
        
        
        if (data.target_role !== undefined) updatePayload.target_role = data.target_role;
        
        
        if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.pinned !== undefined) updatePayload.pinned = data.pinned;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.school !== undefined) {
            await announcements.setSchool(
              
              data.school,
              
              { transaction }
            );
        }
        
        if (data.classroom !== undefined) {
            await announcements.setClassroom(
              
              data.classroom,
              
              { transaction }
            );
        }
        
        if (data.posted_by !== undefined) {
            await announcements.setPosted_by(
              
              data.posted_by,
              
              { transaction }
            );
        }
        

        
        

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

        return announcements;
    }

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

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

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


        return announcements;
    }

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

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

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

        await announcements.destroy({
            transaction
        });

        return announcements;
    }

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

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

        if (!announcements) {
            return announcements;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.notifications_announcement = await announcements.getNotifications_announcement({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.school = await announcements.getSchool({
            transaction
        });
        
        
        output.classroom = await announcements.getClassroom({
            transaction
        });
        
        
        output.posted_by = await announcements.getPosted_by({
            transaction
        });
        
        
        output.attachments = await announcements.getAttachments({
            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 userSchools = (user && user.schools?.id) || null;
        

        
        if (userSchools) {
            if (options?.currentUser?.schoolsId) {
                where.schoolsId = options.currentUser.schoolsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

      {
        model: db.schools,
        as: 'school',
        
      },

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

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



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

    ];

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

            
            if (filter.announcement_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'announcements',
                        'announcement_title',
                        filter.announcement_title,
                    ),
                };
            }
            
            if (filter.announcement_body) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'announcements',
                        'announcement_body',
                        filter.announcement_body,
                    ),
                };
            }
            

            
            

            
            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.expires_atRange) {
                const [start, end] = filter.expires_atRange;

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

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

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

            
            if (filter.audience_type) {
                where = {
                    ...where,
                audience_type: filter.audience_type,
            };
            }
            
            if (filter.target_role) {
                where = {
                    ...where,
                target_role: filter.target_role,
            };
            }
            
            if (filter.pinned) {
                where = {
                    ...where,
                pinned: filter.pinned,
            };
            }
            


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

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

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

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

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

    
};

