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

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

        const approval_reviews = await db.approval_reviews.create(
            {
                id: data.id || undefined,
        
        review_target: data.review_target
        ||
        null
            ,
            
        reviewed_at: data.reviewed_at
        ||
        null
            ,
            
        decision: data.decision
        ||
        null
            ,
            
        alignment_score: data.alignment_score
        ||
        null
            ,
            
        review_notes: data.review_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await approval_reviews.setReviewed_by( data.reviewed_by || null, {
            transaction,
        });
        

        

        

        return approval_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 approval_reviewsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                review_target: item.review_target
            ||
            null
            ,
            
                reviewed_at: item.reviewed_at
            ||
            null
            ,
            
                decision: item.decision
            ||
            null
            ,
            
                alignment_score: item.alignment_score
            ||
            null
            ,
            
                review_notes: item.review_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return approval_reviews;
    }

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

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


        

        const updatePayload = {};
        
        if (data.review_target !== undefined) updatePayload.review_target = data.review_target;
        
        
        if (data.reviewed_at !== undefined) updatePayload.reviewed_at = data.reviewed_at;
        
        
        if (data.decision !== undefined) updatePayload.decision = data.decision;
        
        
        if (data.alignment_score !== undefined) updatePayload.alignment_score = data.alignment_score;
        
        
        if (data.review_notes !== undefined) updatePayload.review_notes = data.review_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.reviewed_by !== undefined) {
            await approval_reviews.setReviewed_by(
              
              data.reviewed_by,
              
              { transaction }
            );
        }
        

        
        

        

        return approval_reviews;
    }

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

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

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


        return approval_reviews;
    }

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

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

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

        await approval_reviews.destroy({
            transaction
        });

        return approval_reviews;
    }

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

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

        if (!approval_reviews) {
            return approval_reviews;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.reviewed_by = await approval_reviews.getReviewed_by({
            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: 'reviewed_by',
        
        where: filter.reviewed_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.reviewed_by.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.reviewed_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.review_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'approval_reviews',
                        'review_notes',
                        filter.review_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      



            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.approval_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(
                        'approval_reviews',
                        'review_notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

