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

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

        const load_stops = await db.load_stops.create(
            {
                id: data.id || undefined,
        
        type: data.type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        sequence: data.sequence
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        address_line1: data.address_line1
        ||
        null
            ,
            
        address_line2: data.address_line2
        ||
        null
            ,
            
        postal_code: data.postal_code
        ||
        null
            ,
            
        city: data.city
        ||
        null
            ,
            
        state: data.state
        ||
        null
            ,
            
        country_code: data.country_code
        ||
        null
            ,
            
        window_start_at: data.window_start_at
        ||
        null
            ,
            
        window_end_at: data.window_end_at
        ||
        null
            ,
            
        planned_at: data.planned_at
        ||
        null
            ,
            
        arrived_at: data.arrived_at
        ||
        null
            ,
            
        departed_at: data.departed_at
        ||
        null
            ,
            
        contact_name: data.contact_name
        ||
        null
            ,
            
        contact_phone: data.contact_phone
        ||
        null
            ,
            
        contact_email: data.contact_email
        ||
        null
            ,
            
        instructions: data.instructions
        ||
        null
            ,
            
        reference_no: data.reference_no
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await load_stops.setCompany( data.company || null, {
            transaction,
        });
        
        await load_stops.setLoad( data.load || null, {
            transaction,
        });
        

        

        

        return load_stops;
    }
    

    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 load_stopsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                type: item.type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                sequence: item.sequence
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                address_line1: item.address_line1
            ||
            null
            ,
            
                address_line2: item.address_line2
            ||
            null
            ,
            
                postal_code: item.postal_code
            ||
            null
            ,
            
                city: item.city
            ||
            null
            ,
            
                state: item.state
            ||
            null
            ,
            
                country_code: item.country_code
            ||
            null
            ,
            
                window_start_at: item.window_start_at
            ||
            null
            ,
            
                window_end_at: item.window_end_at
            ||
            null
            ,
            
                planned_at: item.planned_at
            ||
            null
            ,
            
                arrived_at: item.arrived_at
            ||
            null
            ,
            
                departed_at: item.departed_at
            ||
            null
            ,
            
                contact_name: item.contact_name
            ||
            null
            ,
            
                contact_phone: item.contact_phone
            ||
            null
            ,
            
                contact_email: item.contact_email
            ||
            null
            ,
            
                instructions: item.instructions
            ||
            null
            ,
            
                reference_no: item.reference_no
            ||
            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 load_stops = await db.load_stops.bulkCreate(load_stopsData, { transaction });

        // For each item created, replace relation files
        

        return load_stops;
    }

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

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


        

        const updatePayload = {};
        
        if (data.type !== undefined) updatePayload.type = data.type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.sequence !== undefined) updatePayload.sequence = data.sequence;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.address_line1 !== undefined) updatePayload.address_line1 = data.address_line1;
        
        
        if (data.address_line2 !== undefined) updatePayload.address_line2 = data.address_line2;
        
        
        if (data.postal_code !== undefined) updatePayload.postal_code = data.postal_code;
        
        
        if (data.city !== undefined) updatePayload.city = data.city;
        
        
        if (data.state !== undefined) updatePayload.state = data.state;
        
        
        if (data.country_code !== undefined) updatePayload.country_code = data.country_code;
        
        
        if (data.window_start_at !== undefined) updatePayload.window_start_at = data.window_start_at;
        
        
        if (data.window_end_at !== undefined) updatePayload.window_end_at = data.window_end_at;
        
        
        if (data.planned_at !== undefined) updatePayload.planned_at = data.planned_at;
        
        
        if (data.arrived_at !== undefined) updatePayload.arrived_at = data.arrived_at;
        
        
        if (data.departed_at !== undefined) updatePayload.departed_at = data.departed_at;
        
        
        if (data.contact_name !== undefined) updatePayload.contact_name = data.contact_name;
        
        
        if (data.contact_phone !== undefined) updatePayload.contact_phone = data.contact_phone;
        
        
        if (data.contact_email !== undefined) updatePayload.contact_email = data.contact_email;
        
        
        if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
        
        
        if (data.reference_no !== undefined) updatePayload.reference_no = data.reference_no;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await load_stops.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.load !== undefined) {
            await load_stops.setLoad(
              
              data.load,
              
              { transaction }
            );
        }
        

        
        

        

        return load_stops;
    }

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

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

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


        return load_stops;
    }

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

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

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

        await load_stops.destroy({
            transaction
        });

        return load_stops;
    }

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

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

        if (!load_stops) {
            return load_stops;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.pod_files_stop = await load_stops.getPod_files_stop({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.company = await load_stops.getCompany({
            transaction
        });
        
        
        output.load = await load_stops.getLoad({
            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.loads,
        as: 'load',
        
        where: filter.load ? {
          [Op.or]: [
            { id: { [Op.in]: filter.load.split('|').map(term => Utils.uuid(term)) } },
            {
              load_no: {
                [Op.or]: filter.load.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'load_stops',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.address_line1) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'load_stops',
                        'address_line1',
                        filter.address_line1,
                    ),
                };
            }
            
            if (filter.address_line2) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'load_stops',
                        'address_line2',
                        filter.address_line2,
                    ),
                };
            }
            
            if (filter.postal_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'load_stops',
                        'postal_code',
                        filter.postal_code,
                    ),
                };
            }
            
            if (filter.city) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'load_stops',
                        'city',
                        filter.city,
                    ),
                };
            }
            
            if (filter.state) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'load_stops',
                        'state',
                        filter.state,
                    ),
                };
            }
            
            if (filter.country_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'load_stops',
                        'country_code',
                        filter.country_code,
                    ),
                };
            }
            
            if (filter.contact_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'load_stops',
                        'contact_name',
                        filter.contact_name,
                    ),
                };
            }
            
            if (filter.contact_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'load_stops',
                        'contact_phone',
                        filter.contact_phone,
                    ),
                };
            }
            
            if (filter.contact_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'load_stops',
                        'contact_email',
                        filter.contact_email,
                    ),
                };
            }
            
            if (filter.instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'load_stops',
                        'instructions',
                        filter.instructions,
                    ),
                };
            }
            
            if (filter.reference_no) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'load_stops',
                        'reference_no',
                        filter.reference_no,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'load_stops',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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


      

      



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

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

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

    
};

