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

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

        const organization_settings = await db.organization_settings.create(
            {
                id: data.id || undefined,
        
        default_currency_code: data.default_currency_code
        ||
        null
            ,
            
        default_language: data.default_language
        ||
        null
            ,
            
        default_timezone: data.default_timezone
        ||
        null
            ,
            
        invoice_prefix: data.invoice_prefix
        ||
        null
            ,
            
        quote_prefix: data.quote_prefix
        ||
        null
            ,
            
        receipt_prefix: data.receipt_prefix
        ||
        null
            ,
            
        default_vat_rate: data.default_vat_rate
        ||
        null
            ,
            
        prices_include_tax: data.prices_include_tax
        ||
        false
        
            ,
            
        enable_inventory: data.enable_inventory
        ||
        false
        
            ,
            
        enable_projects: data.enable_projects
        ||
        false
        
            ,
            
        enable_approvals: data.enable_approvals
        ||
        false
        
            ,
            
        invoice_footer_note: data.invoice_footer_note
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await organization_settings.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        

        

        

        return organization_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 organization_settingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                default_currency_code: item.default_currency_code
            ||
            null
            ,
            
                default_language: item.default_language
            ||
            null
            ,
            
                default_timezone: item.default_timezone
            ||
            null
            ,
            
                invoice_prefix: item.invoice_prefix
            ||
            null
            ,
            
                quote_prefix: item.quote_prefix
            ||
            null
            ,
            
                receipt_prefix: item.receipt_prefix
            ||
            null
            ,
            
                default_vat_rate: item.default_vat_rate
            ||
            null
            ,
            
                prices_include_tax: item.prices_include_tax
            ||
            false
        
            ,
            
                enable_inventory: item.enable_inventory
            ||
            false
        
            ,
            
                enable_projects: item.enable_projects
            ||
            false
        
            ,
            
                enable_approvals: item.enable_approvals
            ||
            false
        
            ,
            
                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 organization_settings = await db.organization_settings.bulkCreate(organization_settingsData, { transaction });

        // For each item created, replace relation files
        

        return organization_settings;
    }

    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 organization_settings = await db.organization_settings.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.default_currency_code !== undefined) updatePayload.default_currency_code = data.default_currency_code;
        
        
        if (data.default_language !== undefined) updatePayload.default_language = data.default_language;
        
        
        if (data.default_timezone !== undefined) updatePayload.default_timezone = data.default_timezone;
        
        
        if (data.invoice_prefix !== undefined) updatePayload.invoice_prefix = data.invoice_prefix;
        
        
        if (data.quote_prefix !== undefined) updatePayload.quote_prefix = data.quote_prefix;
        
        
        if (data.receipt_prefix !== undefined) updatePayload.receipt_prefix = data.receipt_prefix;
        
        
        if (data.default_vat_rate !== undefined) updatePayload.default_vat_rate = data.default_vat_rate;
        
        
        if (data.prices_include_tax !== undefined) updatePayload.prices_include_tax = data.prices_include_tax;
        
        
        if (data.enable_inventory !== undefined) updatePayload.enable_inventory = data.enable_inventory;
        
        
        if (data.enable_projects !== undefined) updatePayload.enable_projects = data.enable_projects;
        
        
        if (data.enable_approvals !== undefined) updatePayload.enable_approvals = data.enable_approvals;
        
        
        if (data.invoice_footer_note !== undefined) updatePayload.invoice_footer_note = data.invoice_footer_note;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return organization_settings;
    }

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

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

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


        return organization_settings;
    }

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

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

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

        await organization_settings.destroy({
            transaction
        });

        return organization_settings;
    }

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

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

        if (!organization_settings) {
            return organization_settings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await organization_settings.getOrganization({
            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',
        
      },



    ];

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

            
            if (filter.default_currency_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'organization_settings',
                        'default_currency_code',
                        filter.default_currency_code,
                    ),
                };
            }
            
            if (filter.default_language) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'organization_settings',
                        'default_language',
                        filter.default_language,
                    ),
                };
            }
            
            if (filter.default_timezone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'organization_settings',
                        'default_timezone',
                        filter.default_timezone,
                    ),
                };
            }
            
            if (filter.invoice_prefix) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'organization_settings',
                        'invoice_prefix',
                        filter.invoice_prefix,
                    ),
                };
            }
            
            if (filter.quote_prefix) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'organization_settings',
                        'quote_prefix',
                        filter.quote_prefix,
                    ),
                };
            }
            
            if (filter.receipt_prefix) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'organization_settings',
                        'receipt_prefix',
                        filter.receipt_prefix,
                    ),
                };
            }
            
            if (filter.invoice_footer_note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'organization_settings',
                        'invoice_footer_note',
                        filter.invoice_footer_note,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.prices_include_tax) {
                where = {
                    ...where,
                prices_include_tax: filter.prices_include_tax,
            };
            }
            
            if (filter.enable_inventory) {
                where = {
                    ...where,
                enable_inventory: filter.enable_inventory,
            };
            }
            
            if (filter.enable_projects) {
                where = {
                    ...where,
                enable_projects: filter.enable_projects,
            };
            }
            
            if (filter.enable_approvals) {
                where = {
                    ...where,
                enable_approvals: filter.enable_approvals,
            };
            }
            


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

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

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

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

    
};

