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

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

        const settings = await db.settings.create(
            {
                id: data.id || undefined,
        
        company_name: data.company_name
        ||
        null
            ,
            
        legal_name: data.legal_name
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        city: data.city
        ||
        null
            ,
            
        country: data.country
        ||
        null
            ,
            
        tax_id: data.tax_id
        ||
        null
            ,
            
        primary_color: data.primary_color
        ||
        null
            ,
            
        secondary_color: data.secondary_color
        ||
        null
            ,
            
        theme: data.theme
        ||
        null
            ,
            
        invoice_prefix: data.invoice_prefix
        ||
        null
            ,
            
        quote_prefix: data.quote_prefix
        ||
        null
            ,
            
        sale_prefix: data.sale_prefix
        ||
        null
            ,
            
        invoice_next_number: data.invoice_next_number
        ||
        null
            ,
            
        quote_next_number: data.quote_next_number
        ||
        null
            ,
            
        sale_next_number: data.sale_next_number
        ||
        null
            ,
            
        invoice_footer_note: data.invoice_footer_note
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.settings.getTableName(),
                belongsToColumn: 'logo',
                belongsToId: settings.id,
            },
            data.logo,
            options,
        );
        

        return settings;
    }
    

    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 settingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                company_name: item.company_name
            ||
            null
            ,
            
                legal_name: item.legal_name
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                city: item.city
            ||
            null
            ,
            
                country: item.country
            ||
            null
            ,
            
                tax_id: item.tax_id
            ||
            null
            ,
            
                primary_color: item.primary_color
            ||
            null
            ,
            
                secondary_color: item.secondary_color
            ||
            null
            ,
            
                theme: item.theme
            ||
            null
            ,
            
                invoice_prefix: item.invoice_prefix
            ||
            null
            ,
            
                quote_prefix: item.quote_prefix
            ||
            null
            ,
            
                sale_prefix: item.sale_prefix
            ||
            null
            ,
            
                invoice_next_number: item.invoice_next_number
            ||
            null
            ,
            
                quote_next_number: item.quote_next_number
            ||
            null
            ,
            
                sale_next_number: item.sale_next_number
            ||
            null
            ,
            
                invoice_footer_note: item.invoice_footer_note
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < settings.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.settings.getTableName(),
                    belongsToColumn: 'logo',
                    belongsToId: settings[i].id,
                },
                data[i].logo,
                options,
            );
        }
        

        return settings;
    }

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

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


        

        const updatePayload = {};
        
        if (data.company_name !== undefined) updatePayload.company_name = data.company_name;
        
        
        if (data.legal_name !== undefined) updatePayload.legal_name = data.legal_name;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        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.primary_color !== undefined) updatePayload.primary_color = data.primary_color;
        
        
        if (data.secondary_color !== undefined) updatePayload.secondary_color = data.secondary_color;
        
        
        if (data.theme !== undefined) updatePayload.theme = data.theme;
        
        
        if (data.invoice_prefix !== undefined) updatePayload.invoice_prefix = data.invoice_prefix;
        
        
        if (data.quote_prefix !== undefined) updatePayload.quote_prefix = data.quote_prefix;
        
        
        if (data.sale_prefix !== undefined) updatePayload.sale_prefix = data.sale_prefix;
        
        
        if (data.invoice_next_number !== undefined) updatePayload.invoice_next_number = data.invoice_next_number;
        
        
        if (data.quote_next_number !== undefined) updatePayload.quote_next_number = data.quote_next_number;
        
        
        if (data.sale_next_number !== undefined) updatePayload.sale_next_number = data.sale_next_number;
        
        
        if (data.invoice_footer_note !== undefined) updatePayload.invoice_footer_note = data.invoice_footer_note;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.settings.getTableName(),
                belongsToColumn: 'logo',
                belongsToId: settings.id,
            },
            data.logo,
            options,
        );
        

        return settings;
    }

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

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

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


        return settings;
    }

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

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

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

        await settings.destroy({
            transaction
        });

        return settings;
    }

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

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

        if (!settings) {
            return settings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.logo = await settings.getLogo({
            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.file,
        as: 'logo',
      },

    ];

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

            
            if (filter.company_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'settings',
                        'company_name',
                        filter.company_name,
                    ),
                };
            }
            
            if (filter.legal_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'settings',
                        'legal_name',
                        filter.legal_name,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'settings',
                        'address',
                        filter.address,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'settings',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'settings',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.city) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'settings',
                        'city',
                        filter.city,
                    ),
                };
            }
            
            if (filter.country) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'settings',
                        'country',
                        filter.country,
                    ),
                };
            }
            
            if (filter.tax_id) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'settings',
                        'tax_id',
                        filter.tax_id,
                    ),
                };
            }
            
            if (filter.primary_color) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'settings',
                        'primary_color',
                        filter.primary_color,
                    ),
                };
            }
            
            if (filter.secondary_color) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'settings',
                        'secondary_color',
                        filter.secondary_color,
                    ),
                };
            }
            
            if (filter.invoice_prefix) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'settings',
                        'invoice_prefix',
                        filter.invoice_prefix,
                    ),
                };
            }
            
            if (filter.quote_prefix) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'settings',
                        'quote_prefix',
                        filter.quote_prefix,
                    ),
                };
            }
            
            if (filter.sale_prefix) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'settings',
                        'sale_prefix',
                        filter.sale_prefix,
                    ),
                };
            }
            
            if (filter.invoice_footer_note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'settings',
                        'invoice_footer_note',
                        filter.invoice_footer_note,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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




            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.settings.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(
                        'settings',
                        'company_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

