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

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

        const incidents = await db.incidents.create(
            {
                id: data.id || undefined,
        
        type: data.type
        ||
        null
            ,
            
        occurred_at: data.occurred_at
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        location: data.location
        ||
        null
            ,
            
        paid: data.paid
        ||
        false
        
            ,
            
        paid_at: data.paid_at
        ||
        null
            ,
            
        points: data.points
        ||
        null
            ,
            
        severity: data.severity
        ||
        null
            ,
            
        reported_by: data.reported_by
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await incidents.setCompany( data.company || null, {
            transaction,
        });
        
        await incidents.setEmployee( data.employee || null, {
            transaction,
        });
        
        await incidents.setDriver_profile( data.driver_profile || null, {
            transaction,
        });
        

        

        

        return incidents;
    }
    

    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 incidentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                type: item.type
            ||
            null
            ,
            
                occurred_at: item.occurred_at
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                location: item.location
            ||
            null
            ,
            
                paid: item.paid
            ||
            false
        
            ,
            
                paid_at: item.paid_at
            ||
            null
            ,
            
                points: item.points
            ||
            null
            ,
            
                severity: item.severity
            ||
            null
            ,
            
                reported_by: item.reported_by
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return incidents;
    }

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

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


        

        const updatePayload = {};
        
        if (data.type !== undefined) updatePayload.type = data.type;
        
        
        if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.location !== undefined) updatePayload.location = data.location;
        
        
        if (data.paid !== undefined) updatePayload.paid = data.paid;
        
        
        if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
        
        
        if (data.points !== undefined) updatePayload.points = data.points;
        
        
        if (data.severity !== undefined) updatePayload.severity = data.severity;
        
        
        if (data.reported_by !== undefined) updatePayload.reported_by = data.reported_by;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await incidents.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.employee !== undefined) {
            await incidents.setEmployee(
              
              data.employee,
              
              { transaction }
            );
        }
        
        if (data.driver_profile !== undefined) {
            await incidents.setDriver_profile(
              
              data.driver_profile,
              
              { transaction }
            );
        }
        

        
        

        

        return incidents;
    }

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

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

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


        return incidents;
    }

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

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

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

        await incidents.destroy({
            transaction
        });

        return incidents;
    }

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

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

        if (!incidents) {
            return incidents;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await incidents.getCompany({
            transaction
        });
        
        
        output.employee = await incidents.getEmployee({
            transaction
        });
        
        
        output.driver_profile = await incidents.getDriver_profile({
            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.companies,
        as: 'company',
        
        where: filter.company ? {
          [Op.or]: [
            { id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'incidents',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'incidents',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.location) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'incidents',
                        'location',
                        filter.location,
                    ),
                };
            }
            
            if (filter.severity) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'incidents',
                        'severity',
                        filter.severity,
                    ),
                };
            }
            
            if (filter.reported_by) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'incidents',
                        'reported_by',
                        filter.reported_by,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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


      

      

      



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

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

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

    
};

