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

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

        const locations = await db.locations.create(
            {
                id: data.id || undefined,
        
        location_name: data.location_name
        ||
        null
            ,
            
        location_type: data.location_type
        ||
        null
            ,
            
        address_line_1: data.address_line_1
        ||
        null
            ,
            
        address_line_2: data.address_line_2
        ||
        null
            ,
            
        city: data.city
        ||
        null
            ,
            
        state: data.state
        ||
        null
            ,
            
        postal_code: data.postal_code
        ||
        null
            ,
            
        country: data.country
        ||
        null
            ,
            
        delivery_instructions: data.delivery_instructions
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await locations.setAccount( data.account || null, {
            transaction,
        });
        
        await locations.setDefault_contact( data.default_contact || null, {
            transaction,
        });
        

        

        

        return locations;
    }
    

    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 locationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                location_name: item.location_name
            ||
            null
            ,
            
                location_type: item.location_type
            ||
            null
            ,
            
                address_line_1: item.address_line_1
            ||
            null
            ,
            
                address_line_2: item.address_line_2
            ||
            null
            ,
            
                city: item.city
            ||
            null
            ,
            
                state: item.state
            ||
            null
            ,
            
                postal_code: item.postal_code
            ||
            null
            ,
            
                country: item.country
            ||
            null
            ,
            
                delivery_instructions: item.delivery_instructions
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return locations;
    }

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

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


        

        const updatePayload = {};
        
        if (data.location_name !== undefined) updatePayload.location_name = data.location_name;
        
        
        if (data.location_type !== undefined) updatePayload.location_type = data.location_type;
        
        
        if (data.address_line_1 !== undefined) updatePayload.address_line_1 = data.address_line_1;
        
        
        if (data.address_line_2 !== undefined) updatePayload.address_line_2 = data.address_line_2;
        
        
        if (data.city !== undefined) updatePayload.city = data.city;
        
        
        if (data.state !== undefined) updatePayload.state = data.state;
        
        
        if (data.postal_code !== undefined) updatePayload.postal_code = data.postal_code;
        
        
        if (data.country !== undefined) updatePayload.country = data.country;
        
        
        if (data.delivery_instructions !== undefined) updatePayload.delivery_instructions = data.delivery_instructions;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.account !== undefined) {
            await locations.setAccount(
              
              data.account,
              
              { transaction }
            );
        }
        
        if (data.default_contact !== undefined) {
            await locations.setDefault_contact(
              
              data.default_contact,
              
              { transaction }
            );
        }
        

        
        

        

        return locations;
    }

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

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

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


        return locations;
    }

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

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

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

        await locations.destroy({
            transaction
        });

        return locations;
    }

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

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

        if (!locations) {
            return locations;
        }

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

        
        
        
        
        
        
        output.contacts_location = await locations.getContacts_location({
            transaction
        });
        
        
        
        
        
        
        
        
        output.carts_location = await locations.getCarts_location({
            transaction
        });
        
        
        
        output.orders_location = await locations.getOrders_location({
            transaction
        });
        
        
        
        
        output.quotes_location = await locations.getQuotes_location({
            transaction
        });
        
        
        
        output.sample_requests_location = await locations.getSample_requests_location({
            transaction
        });
        
        
        
        
        
        output.account = await locations.getAccount({
            transaction
        });
        
        
        output.default_contact = await locations.getDefault_contact({
            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.accounts,
        as: 'account',
        
        where: filter.account ? {
          [Op.or]: [
            { id: { [Op.in]: filter.account.split('|').map(term => Utils.uuid(term)) } },
            {
              account_name: {
                [Op.or]: filter.account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.location_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'locations',
                        'location_name',
                        filter.location_name,
                    ),
                };
            }
            
            if (filter.address_line_1) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'locations',
                        'address_line_1',
                        filter.address_line_1,
                    ),
                };
            }
            
            if (filter.address_line_2) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'locations',
                        'address_line_2',
                        filter.address_line_2,
                    ),
                };
            }
            
            if (filter.city) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'locations',
                        'city',
                        filter.city,
                    ),
                };
            }
            
            if (filter.state) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'locations',
                        'state',
                        filter.state,
                    ),
                };
            }
            
            if (filter.postal_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'locations',
                        'postal_code',
                        filter.postal_code,
                    ),
                };
            }
            
            if (filter.country) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'locations',
                        'country',
                        filter.country,
                    ),
                };
            }
            
            if (filter.delivery_instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'locations',
                        'delivery_instructions',
                        filter.delivery_instructions,
                    ),
                };
            }
            

            
            

            

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

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


      

      



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

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

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

    
};

