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

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

        const inquiries = await db.inquiries.create(
            {
                id: data.id || undefined,
        
        inquiry_type: data.inquiry_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        full_name: data.full_name
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        company_name: data.company_name
        ||
        null
            ,
            
        country: data.country
        ||
        null
            ,
            
        buyer_type: data.buyer_type
        ||
        null
            ,
            
        message: data.message
        ||
        null
            ,
            
        target_volume_kg: data.target_volume_kg
        ||
        null
            ,
            
        incoterm: data.incoterm
        ||
        null
            ,
            
        preferred_contact_method: data.preferred_contact_method
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await inquiries.setRequested_region( data.requested_region || null, {
            transaction,
        });
        
        await inquiries.setRequested_lot( data.requested_lot || null, {
            transaction,
        });
        
        await inquiries.setAssigned_to( data.assigned_to || null, {
            transaction,
        });
        

        

        

        return inquiries;
    }
    

    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 inquiriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                inquiry_type: item.inquiry_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                full_name: item.full_name
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                company_name: item.company_name
            ||
            null
            ,
            
                country: item.country
            ||
            null
            ,
            
                buyer_type: item.buyer_type
            ||
            null
            ,
            
                message: item.message
            ||
            null
            ,
            
                target_volume_kg: item.target_volume_kg
            ||
            null
            ,
            
                incoterm: item.incoterm
            ||
            null
            ,
            
                preferred_contact_method: item.preferred_contact_method
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return inquiries;
    }

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

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


        

        const updatePayload = {};
        
        if (data.inquiry_type !== undefined) updatePayload.inquiry_type = data.inquiry_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.company_name !== undefined) updatePayload.company_name = data.company_name;
        
        
        if (data.country !== undefined) updatePayload.country = data.country;
        
        
        if (data.buyer_type !== undefined) updatePayload.buyer_type = data.buyer_type;
        
        
        if (data.message !== undefined) updatePayload.message = data.message;
        
        
        if (data.target_volume_kg !== undefined) updatePayload.target_volume_kg = data.target_volume_kg;
        
        
        if (data.incoterm !== undefined) updatePayload.incoterm = data.incoterm;
        
        
        if (data.preferred_contact_method !== undefined) updatePayload.preferred_contact_method = data.preferred_contact_method;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.requested_region !== undefined) {
            await inquiries.setRequested_region(
              
              data.requested_region,
              
              { transaction }
            );
        }
        
        if (data.requested_lot !== undefined) {
            await inquiries.setRequested_lot(
              
              data.requested_lot,
              
              { transaction }
            );
        }
        
        if (data.assigned_to !== undefined) {
            await inquiries.setAssigned_to(
              
              data.assigned_to,
              
              { transaction }
            );
        }
        

        
        

        

        return inquiries;
    }

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

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

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


        return inquiries;
    }

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

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

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

        await inquiries.destroy({
            transaction
        });

        return inquiries;
    }

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

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

        if (!inquiries) {
            return inquiries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.requested_region = await inquiries.getRequested_region({
            transaction
        });
        
        
        output.requested_lot = await inquiries.getRequested_lot({
            transaction
        });
        
        
        output.assigned_to = await inquiries.getAssigned_to({
            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.coffee_regions,
        as: 'requested_region',
        
        where: filter.requested_region ? {
          [Op.or]: [
            { id: { [Op.in]: filter.requested_region.split('|').map(term => Utils.uuid(term)) } },
            {
              region_name: {
                [Op.or]: filter.requested_region.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.full_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inquiries',
                        'full_name',
                        filter.full_name,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inquiries',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inquiries',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.company_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inquiries',
                        'company_name',
                        filter.company_name,
                    ),
                };
            }
            
            if (filter.country) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inquiries',
                        'country',
                        filter.country,
                    ),
                };
            }
            
            if (filter.message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inquiries',
                        'message',
                        filter.message,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.inquiry_type) {
                where = {
                    ...where,
                inquiry_type: filter.inquiry_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.buyer_type) {
                where = {
                    ...where,
                buyer_type: filter.buyer_type,
            };
            }
            
            if (filter.incoterm) {
                where = {
                    ...where,
                incoterm: filter.incoterm,
            };
            }
            
            if (filter.preferred_contact_method) {
                where = {
                    ...where,
                preferred_contact_method: filter.preferred_contact_method,
            };
            }
            


      

      

      



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

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

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

    
};

