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

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

        const disciplinary_actions = await db.disciplinary_actions.create(
            {
                id: data.id || undefined,
        
        level: data.level
        ||
        null
            ,
            
        issued_at: data.issued_at
        ||
        null
            ,
            
        valid_until: data.valid_until
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await disciplinary_actions.setEmployee( data.employee || null, {
            transaction,
        });
        
        await disciplinary_actions.setOutlet( data.outlet || null, {
            transaction,
        });
        
        await disciplinary_actions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return disciplinary_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 disciplinary_actionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                level: item.level
            ||
            null
            ,
            
                issued_at: item.issued_at
            ||
            null
            ,
            
                valid_until: item.valid_until
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

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


        

        const updatePayload = {};
        
        if (data.level !== undefined) updatePayload.level = data.level;
        
        
        if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
        
        
        if (data.valid_until !== undefined) updatePayload.valid_until = data.valid_until;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.employee !== undefined) {
            await disciplinary_actions.setEmployee(
              
              data.employee,
              
              { transaction }
            );
        }
        
        if (data.outlet !== undefined) {
            await disciplinary_actions.setOutlet(
              
              data.outlet,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await disciplinary_actions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return disciplinary_actions;
    }

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

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

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


        return disciplinary_actions;
    }

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

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

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

        await disciplinary_actions.destroy({
            transaction
        });

        return disciplinary_actions;
    }

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

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

        if (!disciplinary_actions) {
            return disciplinary_actions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.employee = await disciplinary_actions.getEmployee({
            transaction
        });
        
        
        output.outlet = await disciplinary_actions.getOutlet({
            transaction
        });
        
        
        output.evidence_files = await disciplinary_actions.getEvidence_files({
            transaction
        });
        
        
        output.organizations = await disciplinary_actions.getOrganizations({
            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.employees,
        as: 'employee',
        
        where: filter.employee ? {
          [Op.or]: [
            { id: { [Op.in]: filter.employee.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.employee.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

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

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

            
            

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

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

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

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

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

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

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


      

      

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

        where = {
          ...where,
          organizationsId: {[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.disciplinary_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(
                        'disciplinary_actions',
                        'description',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

