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

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

        const clients = await db.clients.create(
            {
                id: data.id || undefined,
        
        code: data.code
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        type: data.type
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        city: data.city
        ||
        null
            ,
            
        country: data.country
        ||
        null
            ,
            
        tax_id: data.tax_id
        ||
        null
            ,
            
        credit_limit: data.credit_limit
        ||
        null
            ,
            
        opening_balance: data.opening_balance
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return clients;
    }
    

    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 clientsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                code: item.code
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                type: item.type
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                city: item.city
            ||
            null
            ,
            
                country: item.country
            ||
            null
            ,
            
                tax_id: item.tax_id
            ||
            null
            ,
            
                credit_limit: item.credit_limit
            ||
            null
            ,
            
                opening_balance: item.opening_balance
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return clients;
    }

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

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


        

        const updatePayload = {};
        
        if (data.code !== undefined) updatePayload.code = data.code;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.type !== undefined) updatePayload.type = data.type;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.city !== undefined) updatePayload.city = data.city;
        
        
        if (data.country !== undefined) updatePayload.country = data.country;
        
        
        if (data.tax_id !== undefined) updatePayload.tax_id = data.tax_id;
        
        
        if (data.credit_limit !== undefined) updatePayload.credit_limit = data.credit_limit;
        
        
        if (data.opening_balance !== undefined) updatePayload.opening_balance = data.opening_balance;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return clients;
    }

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

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

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


        return clients;
    }

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

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

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

        await clients.destroy({
            transaction
        });

        return clients;
    }

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

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

        if (!clients) {
            return clients;
        }

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

        
        
        
        
        
        
        
        
        
        output.stock_movements_client = await clients.getStock_movements_client({
            transaction
        });
        
        
        output.quotes_client = await clients.getQuotes_client({
            transaction
        });
        
        
        
        output.sales_client = await clients.getSales_client({
            transaction
        });
        
        
        
        output.invoices_client = await clients.getInvoices_client({
            transaction
        });
        
        
        
        output.payments_client = await clients.getPayments_client({
            transaction
        });
        
        
        
        
        
        
        
        output.alerts_client = await clients.getAlerts_client({
            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 = [



    ];

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

            
            if (filter.code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clients',
                        'code',
                        filter.code,
                    ),
                };
            }
            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clients',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clients',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clients',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clients',
                        'address',
                        filter.address,
                    ),
                };
            }
            
            if (filter.city) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clients',
                        'city',
                        filter.city,
                    ),
                };
            }
            
            if (filter.country) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clients',
                        'country',
                        filter.country,
                    ),
                };
            }
            
            if (filter.tax_id) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clients',
                        'tax_id',
                        filter.tax_id,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clients',
                        '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.opening_balanceRange) {
                const [start, end] = filter.opening_balanceRange;

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

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

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

            
            if (filter.type) {
                where = {
                    ...where,
                type: filter.type,
            };
            }
            
            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.clients.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(
                        'clients',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

