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

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

        const review_actions = await db.review_actions.create(
            {
                id: data.id || undefined,
        
        action_type: data.action_type
        ||
        null
            ,
            
        correction_json: data.correction_json
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        action_at: data.action_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await review_actions.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await review_actions.setAuthorization_case( data.authorization_case || null, {
            transaction,
        });
        
        await review_actions.setAi_output( data.ai_output || null, {
            transaction,
        });
        
        await review_actions.setReviewer_user( data.reviewer_user || null, {
            transaction,
        });
        

        

        

        return review_actions;
    }
    

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

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

        // For each item created, replace relation files
        

        return review_actions;
    }

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


        

        const updatePayload = {};
        
        if (data.action_type !== undefined) updatePayload.action_type = data.action_type;
        
        
        if (data.correction_json !== undefined) updatePayload.correction_json = data.correction_json;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.action_at !== undefined) updatePayload.action_at = data.action_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await review_actions.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.authorization_case !== undefined) {
            await review_actions.setAuthorization_case(
              
              data.authorization_case,
              
              { transaction }
            );
        }
        
        if (data.ai_output !== undefined) {
            await review_actions.setAi_output(
              
              data.ai_output,
              
              { transaction }
            );
        }
        
        if (data.reviewer_user !== undefined) {
            await review_actions.setReviewer_user(
              
              data.reviewer_user,
              
              { transaction }
            );
        }
        

        
        

        

        return review_actions;
    }

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

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

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


        return review_actions;
    }

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

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

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

        await review_actions.destroy({
            transaction
        });

        return review_actions;
    }

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

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

        if (!review_actions) {
            return review_actions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await review_actions.getOrganization({
            transaction
        });
        
        
        output.authorization_case = await review_actions.getAuthorization_case({
            transaction
        });
        
        
        output.ai_output = await review_actions.getAi_output({
            transaction
        });
        
        
        output.reviewer_user = await review_actions.getReviewer_user({
            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 userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

      {
        model: db.organizations,
        as: 'organization',
        
      },

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

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

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



    ];

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

            
            if (filter.correction_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'review_actions',
                        'correction_json',
                        filter.correction_json,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'review_actions',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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


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

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

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

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

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

    
};

