
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,
        
        display_name: data.display_name
        ||
        null
            ,
            
        company_name: data.company_name
        ||
        null
            ,
            
        contact_name: data.contact_name
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        city: data.city
        ||
        null
            ,
            
        ice: data.ice
        ||
        null
            ,
            
        if_number: data.if_number
        ||
        null
            ,
            
        rc: data.rc
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await clients.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await clients.setPayment_terms( data.payment_terms || null, {
            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,
                
                display_name: item.display_name
            ||
            null
            ,
            
                company_name: item.company_name
            ||
            null
            ,
            
                contact_name: item.contact_name
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                city: item.city
            ||
            null
            ,
            
                ice: item.ice
            ||
            null
            ,
            
                if_number: item.if_number
            ||
            null
            ,
            
                rc: item.rc
            ||
            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 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 globalAccess = currentUser.app_role?.globalAccess;

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


        

        const updatePayload = {};
        
        if (data.display_name !== undefined) updatePayload.display_name = data.display_name;
        
        
        if (data.company_name !== undefined) updatePayload.company_name = data.company_name;
        
        
        if (data.contact_name !== undefined) updatePayload.contact_name = data.contact_name;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.city !== undefined) updatePayload.city = data.city;
        
        
        if (data.ice !== undefined) updatePayload.ice = data.ice;
        
        
        if (data.if_number !== undefined) updatePayload.if_number = data.if_number;
        
        
        if (data.rc !== undefined) updatePayload.rc = data.rc;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await clients.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.payment_terms !== undefined) {
            await clients.setPayment_terms(
              
              data.payment_terms,
              
              { 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.quotes_client = await clients.getQuotes_client({
            transaction
        });
        
        
        
        output.sales_orders_client = await clients.getSales_orders_client({
            transaction
        });
        
        
        
        output.delivery_notes_client = await clients.getDelivery_notes_client({
            transaction
        });
        
        
        
        output.invoices_client = await clients.getInvoices_client({
            transaction
        });
        
        
        
        
        output.credit_notes_client = await clients.getCredit_notes_client({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await clients.getOrganization({
            transaction
        });
        
        
        output.payment_terms = await clients.getPayment_terms({
            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.payment_terms,
        as: 'payment_terms',
        
        where: filter.payment_terms ? {
          [Op.or]: [
            { id: { [Op.in]: filter.payment_terms.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.payment_terms.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.display_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clients',
                        'display_name',
                        filter.display_name,
                    ),
                };
            }
            
            if (filter.company_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clients',
                        'company_name',
                        filter.company_name,
                    ),
                };
            }
            
            if (filter.contact_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clients',
                        'contact_name',
                        filter.contact_name,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clients',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clients',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            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.ice) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clients',
                        'ice',
                        filter.ice,
                    ),
                };
            }
            
            if (filter.if_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clients',
                        'if_number',
                        filter.if_number,
                    ),
                };
            }
            
            if (filter.rc) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clients',
                        'rc',
                        filter.rc,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clients',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      
      if (filter.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

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

      



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

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'clients',
                        'display_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

