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

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

        const management_reviews = await db.management_reviews.create(
            {
                id: data.id || undefined,
        
        review_title: data.review_title
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        meeting_start_at: data.meeting_start_at
        ||
        null
            ,
            
        meeting_end_at: data.meeting_end_at
        ||
        null
            ,
            
        agenda: data.agenda
        ||
        null
            ,
            
        minutes: data.minutes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await management_reviews.setChairperson( data.chairperson || null, {
            transaction,
        });
        

        

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

        return management_reviews;
    }
    

    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 management_reviewsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                review_title: item.review_title
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                meeting_start_at: item.meeting_start_at
            ||
            null
            ,
            
                meeting_end_at: item.meeting_end_at
            ||
            null
            ,
            
                agenda: item.agenda
            ||
            null
            ,
            
                minutes: item.minutes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return management_reviews;
    }

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

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


        

        const updatePayload = {};
        
        if (data.review_title !== undefined) updatePayload.review_title = data.review_title;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.meeting_start_at !== undefined) updatePayload.meeting_start_at = data.meeting_start_at;
        
        
        if (data.meeting_end_at !== undefined) updatePayload.meeting_end_at = data.meeting_end_at;
        
        
        if (data.agenda !== undefined) updatePayload.agenda = data.agenda;
        
        
        if (data.minutes !== undefined) updatePayload.minutes = data.minutes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.chairperson !== undefined) {
            await management_reviews.setChairperson(
              
              data.chairperson,
              
              { transaction }
            );
        }
        

        
        

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

        return management_reviews;
    }

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

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

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


        return management_reviews;
    }

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

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

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

        await management_reviews.destroy({
            transaction
        });

        return management_reviews;
    }

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

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

        if (!management_reviews) {
            return management_reviews;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.chairperson = await management_reviews.getChairperson({
            transaction
        });
        
        
        output.attachments = await management_reviews.getAttachments({
            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.users,
        as: 'chairperson',
        
        where: filter.chairperson ? {
          [Op.or]: [
            { id: { [Op.in]: filter.chairperson.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.chairperson.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.review_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'management_reviews',
                        'review_title',
                        filter.review_title,
                    ),
                };
            }
            
            if (filter.agenda) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'management_reviews',
                        'agenda',
                        filter.agenda,
                    ),
                };
            }
            
            if (filter.minutes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'management_reviews',
                        'minutes',
                        filter.minutes,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            meeting_start_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    meeting_end_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    meeting_start_at: {
                    ...where.meeting_start_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.meeting_end_atRange) {
                const [start, end] = filter.meeting_end_atRange;

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

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

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

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


      



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

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

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

    
};

