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

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

        const accounts = await db.accounts.create(
            {
                id: data.id || undefined,
        
        account_name: data.account_name
        ||
        null
            ,
            
        account_type: data.account_type
        ||
        null
            ,
            
        account_number: data.account_number
        ||
        null
            ,
            
        tax_exempt_number: data.tax_exempt_number
        ||
        null
            ,
            
        is_tax_exempt: data.is_tax_exempt
        ||
        false
        
            ,
            
        credit_status: data.credit_status
        ||
        null
            ,
            
        credit_limit: data.credit_limit
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await accounts.setDefault_price_list( data.default_price_list || null, {
            transaction,
        });
        
        await accounts.setAssigned_sales_rep( data.assigned_sales_rep || null, {
            transaction,
        });
        

        

        

        return accounts;
    }
    

    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 accountsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                account_name: item.account_name
            ||
            null
            ,
            
                account_type: item.account_type
            ||
            null
            ,
            
                account_number: item.account_number
            ||
            null
            ,
            
                tax_exempt_number: item.tax_exempt_number
            ||
            null
            ,
            
                is_tax_exempt: item.is_tax_exempt
            ||
            false
        
            ,
            
                credit_status: item.credit_status
            ||
            null
            ,
            
                credit_limit: item.credit_limit
            ||
            null
            ,
            
                notes: item.notes
            ||
            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 accounts = await db.accounts.bulkCreate(accountsData, { transaction });

        // For each item created, replace relation files
        

        return accounts;
    }

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

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


        

        const updatePayload = {};
        
        if (data.account_name !== undefined) updatePayload.account_name = data.account_name;
        
        
        if (data.account_type !== undefined) updatePayload.account_type = data.account_type;
        
        
        if (data.account_number !== undefined) updatePayload.account_number = data.account_number;
        
        
        if (data.tax_exempt_number !== undefined) updatePayload.tax_exempt_number = data.tax_exempt_number;
        
        
        if (data.is_tax_exempt !== undefined) updatePayload.is_tax_exempt = data.is_tax_exempt;
        
        
        if (data.credit_status !== undefined) updatePayload.credit_status = data.credit_status;
        
        
        if (data.credit_limit !== undefined) updatePayload.credit_limit = data.credit_limit;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.default_price_list !== undefined) {
            await accounts.setDefault_price_list(
              
              data.default_price_list,
              
              { transaction }
            );
        }
        
        if (data.assigned_sales_rep !== undefined) {
            await accounts.setAssigned_sales_rep(
              
              data.assigned_sales_rep,
              
              { transaction }
            );
        }
        

        
        

        

        return accounts;
    }

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

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

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


        return accounts;
    }

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

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

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

        await accounts.destroy({
            transaction
        });

        return accounts;
    }

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

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

        if (!accounts) {
            return accounts;
        }

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

        
        
        
        
        
        output.locations_account = await accounts.getLocations_account({
            transaction
        });
        
        
        output.contacts_account = await accounts.getContacts_account({
            transaction
        });
        
        
        
        
        
        
        
        output.account_price_lists_account = await accounts.getAccount_price_lists_account({
            transaction
        });
        
        
        output.carts_account = await accounts.getCarts_account({
            transaction
        });
        
        
        
        output.orders_account = await accounts.getOrders_account({
            transaction
        });
        
        
        
        
        output.quotes_account = await accounts.getQuotes_account({
            transaction
        });
        
        
        
        output.sample_requests_account = await accounts.getSample_requests_account({
            transaction
        });
        
        
        output.saved_lists_account = await accounts.getSaved_lists_account({
            transaction
        });
        
        
        
        
        output.default_price_list = await accounts.getDefault_price_list({
            transaction
        });
        
        
        output.assigned_sales_rep = await accounts.getAssigned_sales_rep({
            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.price_lists,
        as: 'default_price_list',
        
        where: filter.default_price_list ? {
          [Op.or]: [
            { id: { [Op.in]: filter.default_price_list.split('|').map(term => Utils.uuid(term)) } },
            {
              price_list_name: {
                [Op.or]: filter.default_price_list.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.account_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'accounts',
                        'account_name',
                        filter.account_name,
                    ),
                };
            }
            
            if (filter.account_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'accounts',
                        'account_number',
                        filter.account_number,
                    ),
                };
            }
            
            if (filter.tax_exempt_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'accounts',
                        'tax_exempt_number',
                        filter.tax_exempt_number,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'accounts',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.account_type) {
                where = {
                    ...where,
                account_type: filter.account_type,
            };
            }
            
            if (filter.is_tax_exempt) {
                where = {
                    ...where,
                is_tax_exempt: filter.is_tax_exempt,
            };
            }
            
            if (filter.credit_status) {
                where = {
                    ...where,
                credit_status: filter.credit_status,
            };
            }
            
            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.accounts.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(
                        'accounts',
                        'account_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

