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

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

        const site_settings = await db.site_settings.create(
            {
                id: data.id || undefined,
        
        store_name: data.store_name
        ||
        null
            ,
            
        default_language: data.default_language
        ||
        null
            ,
            
        default_currency: data.default_currency
        ||
        null
            ,
            
        rtl_enabled: data.rtl_enabled
        ||
        false
        
            ,
            
        adsense_head_code: data.adsense_head_code
        ||
        null
            ,
            
        footer_bottom_text: data.footer_bottom_text
        ||
        null
            ,
            
        footer_partner_banner_enabled: data.footer_partner_banner_enabled
        ||
        false
        
            ,
            
        footer_partner_banner_text: data.footer_partner_banner_text
        ||
        null
            ,
            
        footer_partner_banner_url: data.footer_partner_banner_url
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

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

        return site_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 site_settingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                store_name: item.store_name
            ||
            null
            ,
            
                default_language: item.default_language
            ||
            null
            ,
            
                default_currency: item.default_currency
            ||
            null
            ,
            
                rtl_enabled: item.rtl_enabled
            ||
            false
        
            ,
            
                adsense_head_code: item.adsense_head_code
            ||
            null
            ,
            
                footer_bottom_text: item.footer_bottom_text
            ||
            null
            ,
            
                footer_partner_banner_enabled: item.footer_partner_banner_enabled
            ||
            false
        
            ,
            
                footer_partner_banner_text: item.footer_partner_banner_text
            ||
            null
            ,
            
                footer_partner_banner_url: item.footer_partner_banner_url
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return site_settings;
    }

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

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


        

        const updatePayload = {};
        
        if (data.store_name !== undefined) updatePayload.store_name = data.store_name;
        
        
        if (data.default_language !== undefined) updatePayload.default_language = data.default_language;
        
        
        if (data.default_currency !== undefined) updatePayload.default_currency = data.default_currency;
        
        
        if (data.rtl_enabled !== undefined) updatePayload.rtl_enabled = data.rtl_enabled;
        
        
        if (data.adsense_head_code !== undefined) updatePayload.adsense_head_code = data.adsense_head_code;
        
        
        if (data.footer_bottom_text !== undefined) updatePayload.footer_bottom_text = data.footer_bottom_text;
        
        
        if (data.footer_partner_banner_enabled !== undefined) updatePayload.footer_partner_banner_enabled = data.footer_partner_banner_enabled;
        
        
        if (data.footer_partner_banner_text !== undefined) updatePayload.footer_partner_banner_text = data.footer_partner_banner_text;
        
        
        if (data.footer_partner_banner_url !== undefined) updatePayload.footer_partner_banner_url = data.footer_partner_banner_url;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

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

        return site_settings;
    }

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

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

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


        return site_settings;
    }

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

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

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

        await site_settings.destroy({
            transaction
        });

        return site_settings;
    }

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

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

        if (!site_settings) {
            return site_settings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.store_logo = await site_settings.getStore_logo({
            transaction
        });
        
        
        output.footer_partner_banner_image = await site_settings.getFooter_partner_banner_image({
            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: 'store_logo',
      },

      {
        model: db.file,
        as: 'footer_partner_banner_image',
      },

    ];

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

            
            if (filter.store_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'store_name',
                        filter.store_name,
                    ),
                };
            }
            
            if (filter.default_language) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'default_language',
                        filter.default_language,
                    ),
                };
            }
            
            if (filter.default_currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'default_currency',
                        filter.default_currency,
                    ),
                };
            }
            
            if (filter.adsense_head_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'adsense_head_code',
                        filter.adsense_head_code,
                    ),
                };
            }
            
            if (filter.footer_bottom_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'footer_bottom_text',
                        filter.footer_bottom_text,
                    ),
                };
            }
            
            if (filter.footer_partner_banner_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'footer_partner_banner_text',
                        filter.footer_partner_banner_text,
                    ),
                };
            }
            
            if (filter.footer_partner_banner_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'footer_partner_banner_url',
                        filter.footer_partner_banner_url,
                    ),
                };
            }
            

            
            

            

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

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




            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.site_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(
                        'site_settings',
                        'store_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

