
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
            ,
            
        currency_code: data.currency_code
        ||
        null
            ,
            
        exchange_rate: data.exchange_rate
        ||
        null
            ,
            
        subtotal_amount: data.subtotal_amount
        ||
        null
            ,
            
        tax_amount: data.tax_amount
        ||
        null
            ,
            
        discount_amount: data.discount_amount
        ||
        null
            ,
            
        total_amount: data.total_amount
        ||
        null
            ,
            
        customer_notes: data.customer_notes
        ||
        null
            ,
            
        terms_and_conditions: data.terms_and_conditions
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await quotes.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await quotes.setCustomer( data.customer || null, {
            transaction,
        });
        

        
        await quotes.setQuote_lines(data.quote_lines || [], {
            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
            ,
            
                currency_code: item.currency_code
            ||
            null
            ,
            
                exchange_rate: item.exchange_rate
            ||
            null
            ,
            
                subtotal_amount: item.subtotal_amount
            ||
            null
            ,
            
                tax_amount: item.tax_amount
            ||
            null
            ,
            
                discount_amount: item.discount_amount
            ||
            null
            ,
            
                total_amount: item.total_amount
            ||
            null
            ,
            
                customer_notes: item.customer_notes
            ||
            null
            ,
            
                terms_and_conditions: item.terms_and_conditions
            ||
            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 globalAccess = currentUser.app_role?.globalAccess;

        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.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
        
        
        if (data.exchange_rate !== undefined) updatePayload.exchange_rate = data.exchange_rate;
        
        
        if (data.subtotal_amount !== undefined) updatePayload.subtotal_amount = data.subtotal_amount;
        
        
        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_amount !== undefined) updatePayload.total_amount = data.total_amount;
        
        
        if (data.customer_notes !== undefined) updatePayload.customer_notes = data.customer_notes;
        
        
        if (data.terms_and_conditions !== undefined) updatePayload.terms_and_conditions = data.terms_and_conditions;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await quotes.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await quotes.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        

        
        
        if (data.quote_lines !== undefined) {
            await quotes.setQuote_lines(data.quote_lines, { 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_lines_quote = await quotes.getQuote_lines_quote({
            transaction
        });
        
        
        output.invoices_quote = await quotes.getInvoices_quote({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await quotes.getOrganization({
            transaction
        });
        
        
        output.customer = await quotes.getCustomer({
            transaction
        });
        
        
        output.quote_lines = await quotes.getQuote_lines({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.organizations,
        as: 'organization',
        
      },

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


      {
        model: db.quote_lines,
        as: 'quote_lines',
        required: false,
      },


    ];

        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.currency_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'quotes',
                        'currency_code',
                        filter.currency_code,
                    ),
                };
            }
            
            if (filter.customer_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'quotes',
                        'customer_notes',
                        filter.customer_notes,
                    ),
                };
            }
            
            if (filter.terms_and_conditions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'quotes',
                        'terms_and_conditions',
                        filter.terms_and_conditions,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            issue_date: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    valid_until: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

            
            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.exchange_rateRange) {
                const [start, end] = filter.exchange_rateRange;

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    subtotal_amount: {
                    ...where.subtotal_amount,
                            [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.total_amountRange) {
                const [start, end] = filter.total_amountRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    total_amount: {
                    ...where.total_amount,
                            [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.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[Op.or]: listItems}
        };
      }
      

      


      if (filter.quote_lines) {
        const searchTerms = filter.quote_lines.split('|');

        include = [
          {
            model: db.quote_lines,
            as: 'quote_lines_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  line_description: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        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,
        }));
    }

    
};

