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

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

        const loads = await db.loads.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        load_no: data.load_no
        ||
        null
            ,
            
        reference: data.reference
        ||
        null
            ,
            
        equipment: data.equipment
        ||
        null
            ,
            
        cargo_description: data.cargo_description
        ||
        null
            ,
            
        weight_kg: data.weight_kg
        ||
        null
            ,
            
        volume_m3: data.volume_m3
        ||
        null
            ,
            
        pallets: data.pallets
        ||
        null
            ,
            
        pieces: data.pieces
        ||
        null
            ,
            
        temperature_min_c: data.temperature_min_c
        ||
        null
            ,
            
        temperature_max_c: data.temperature_max_c
        ||
        null
            ,
            
        adr_required: data.adr_required
        ||
        false
        
            ,
            
        cmr_number: data.cmr_number
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await loads.setCompany( data.company || null, {
            transaction,
        });
        
        await loads.setOrder( data.order || null, {
            transaction,
        });
        

        

        

        return loads;
    }
    

    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 loadsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                status: item.status
            ||
            null
            ,
            
                load_no: item.load_no
            ||
            null
            ,
            
                reference: item.reference
            ||
            null
            ,
            
                equipment: item.equipment
            ||
            null
            ,
            
                cargo_description: item.cargo_description
            ||
            null
            ,
            
                weight_kg: item.weight_kg
            ||
            null
            ,
            
                volume_m3: item.volume_m3
            ||
            null
            ,
            
                pallets: item.pallets
            ||
            null
            ,
            
                pieces: item.pieces
            ||
            null
            ,
            
                temperature_min_c: item.temperature_min_c
            ||
            null
            ,
            
                temperature_max_c: item.temperature_max_c
            ||
            null
            ,
            
                adr_required: item.adr_required
            ||
            false
        
            ,
            
                cmr_number: item.cmr_number
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return loads;
    }

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

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


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.load_no !== undefined) updatePayload.load_no = data.load_no;
        
        
        if (data.reference !== undefined) updatePayload.reference = data.reference;
        
        
        if (data.equipment !== undefined) updatePayload.equipment = data.equipment;
        
        
        if (data.cargo_description !== undefined) updatePayload.cargo_description = data.cargo_description;
        
        
        if (data.weight_kg !== undefined) updatePayload.weight_kg = data.weight_kg;
        
        
        if (data.volume_m3 !== undefined) updatePayload.volume_m3 = data.volume_m3;
        
        
        if (data.pallets !== undefined) updatePayload.pallets = data.pallets;
        
        
        if (data.pieces !== undefined) updatePayload.pieces = data.pieces;
        
        
        if (data.temperature_min_c !== undefined) updatePayload.temperature_min_c = data.temperature_min_c;
        
        
        if (data.temperature_max_c !== undefined) updatePayload.temperature_max_c = data.temperature_max_c;
        
        
        if (data.adr_required !== undefined) updatePayload.adr_required = data.adr_required;
        
        
        if (data.cmr_number !== undefined) updatePayload.cmr_number = data.cmr_number;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await loads.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.order !== undefined) {
            await loads.setOrder(
              
              data.order,
              
              { transaction }
            );
        }
        

        
        

        

        return loads;
    }

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

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

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


        return loads;
    }

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

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

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

        await loads.destroy({
            transaction
        });

        return loads;
    }

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

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

        if (!loads) {
            return loads;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.load_stops_load = await loads.getLoad_stops_load({
            transaction
        });
        
        
        
        output.trip_loads_load = await loads.getTrip_loads_load({
            transaction
        });
        
        
        
        
        output.invoice_lines_load = await loads.getInvoice_lines_load({
            transaction
        });
        
        
        
        output.cost_items_load = await loads.getCost_items_load({
            transaction
        });
        
        
        
        
        
        
        output.company = await loads.getCompany({
            transaction
        });
        
        
        output.order = await loads.getOrder({
            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.orders,
        as: 'order',
        
        where: filter.order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.order.split('|').map(term => Utils.uuid(term)) } },
            {
              order_no: {
                [Op.or]: filter.order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.load_no) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'loads',
                        'load_no',
                        filter.load_no,
                    ),
                };
            }
            
            if (filter.reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'loads',
                        'reference',
                        filter.reference,
                    ),
                };
            }
            
            if (filter.cargo_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'loads',
                        'cargo_description',
                        filter.cargo_description,
                    ),
                };
            }
            
            if (filter.cmr_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'loads',
                        'cmr_number',
                        filter.cmr_number,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'loads',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    temperature_max_c: {
                    ...where.temperature_max_c,
                            [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.equipment) {
                where = {
                    ...where,
                equipment: filter.equipment,
            };
            }
            
            if (filter.adr_required) {
                where = {
                    ...where,
                adr_required: filter.adr_required,
            };
            }
            


      

      



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

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

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

    
};

