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

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

        const quotes = await db.quotes.create(
            {
                id: data.id || undefined,
        
        quote_number: data.quote_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        issue_date: data.issue_date
        ||
        null
            ,
            
        valid_until: data.valid_until
        ||
        null
            ,
            
        subtotal: data.subtotal
        ||
        null
            ,
            
        tax_amount: data.tax_amount
        ||
        null
            ,
            
        discount_amount: data.discount_amount
        ||
        null
            ,
            
        total: data.total
        ||
        null
            ,
            
        terms: data.terms
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await quotes.setCustomer( data.customer || null, {
            transaction,
        });
        
        await quotes.setLead( data.lead || null, {
            transaction,
        });
        
        await quotes.setPrepared_by( data.prepared_by || null, {
            transaction,
        });
        

        

        

        return quotes;
    }
    

    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 quotesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                quote_number: item.quote_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                issue_date: item.issue_date
            ||
            null
            ,
            
                valid_until: item.valid_until
            ||
            null
            ,
            
                subtotal: item.subtotal
            ||
            null
            ,
            
                tax_amount: item.tax_amount
            ||
            null
            ,
            
                discount_amount: item.discount_amount
            ||
            null
            ,
            
                total: item.total
            ||
            null
            ,
            
                terms: item.terms
            ||
            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 quotes = await db.quotes.bulkCreate(quotesData, { transaction });

        // For each item created, replace relation files
        

        return quotes;
    }

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

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


        

        const updatePayload = {};
        
        if (data.quote_number !== undefined) updatePayload.quote_number = data.quote_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.issue_date !== undefined) updatePayload.issue_date = data.issue_date;
        
        
        if (data.valid_until !== undefined) updatePayload.valid_until = data.valid_until;
        
        
        if (data.subtotal !== undefined) updatePayload.subtotal = data.subtotal;
        
        
        if (data.tax_amount !== undefined) updatePayload.tax_amount = data.tax_amount;
        
        
        if (data.discount_amount !== undefined) updatePayload.discount_amount = data.discount_amount;
        
        
        if (data.total !== undefined) updatePayload.total = data.total;
        
        
        if (data.terms !== undefined) updatePayload.terms = data.terms;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.customer !== undefined) {
            await quotes.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.lead !== undefined) {
            await quotes.setLead(
              
              data.lead,
              
              { transaction }
            );
        }
        
        if (data.prepared_by !== undefined) {
            await quotes.setPrepared_by(
              
              data.prepared_by,
              
              { transaction }
            );
        }
        

        
        

        

        return quotes;
    }

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

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

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


        return quotes;
    }

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

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

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

        await quotes.destroy({
            transaction
        });

        return quotes;
    }

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

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

        if (!quotes) {
            return quotes;
        }

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

        
        
        
        
        
        
        
        
        output.quote_line_items_quote = await quotes.getQuote_line_items_quote({
            transaction
        });
        
        
        output.projects_quote = await quotes.getProjects_quote({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.invoices_quote = await quotes.getInvoices_quote({
            transaction
        });
        
        
        
        
        
        
        output.customer = await quotes.getCustomer({
            transaction
        });
        
        
        output.lead = await quotes.getLead({
            transaction
        });
        
        
        output.prepared_by = await quotes.getPrepared_by({
            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.customers,
        as: 'customer',
        
        where: filter.customer ? {
          [Op.or]: [
            { id: { [Op.in]: filter.customer.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.customer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.quote_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'quotes',
                        'quote_number',
                        filter.quote_number,
                    ),
                };
            }
            
            if (filter.terms) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'quotes',
                        'terms',
                        filter.terms,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'quotes',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    total: {
                    ...where.total,
                            [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.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.quotes.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(
                        'quotes',
                        'quote_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

