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

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

        const store_settings = await db.store_settings.create(
            {
                id: data.id || undefined,
        
        store_name: data.store_name
        ||
        null
            ,
            
        store_tagline: data.store_tagline
        ||
        null
            ,
            
        support_email: data.support_email
        ||
        null
            ,
            
        support_phone: data.support_phone
        ||
        null
            ,
            
        whatsapp_number: data.whatsapp_number
        ||
        null
            ,
            
        currency_code: data.currency_code
        ||
        null
            ,
            
        timezone: data.timezone
        ||
        null
            ,
            
        primary_color_hex: data.primary_color_hex
        ||
        null
            ,
            
        secondary_color_hex: data.secondary_color_hex
        ||
        null
            ,
            
        maintenance_mode: data.maintenance_mode
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

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

        return store_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 store_settingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                store_name: item.store_name
            ||
            null
            ,
            
                store_tagline: item.store_tagline
            ||
            null
            ,
            
                support_email: item.support_email
            ||
            null
            ,
            
                support_phone: item.support_phone
            ||
            null
            ,
            
                whatsapp_number: item.whatsapp_number
            ||
            null
            ,
            
                currency_code: item.currency_code
            ||
            null
            ,
            
                timezone: item.timezone
            ||
            null
            ,
            
                primary_color_hex: item.primary_color_hex
            ||
            null
            ,
            
                secondary_color_hex: item.secondary_color_hex
            ||
            null
            ,
            
                maintenance_mode: item.maintenance_mode
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return store_settings;
    }

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

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


        

        const updatePayload = {};
        
        if (data.store_name !== undefined) updatePayload.store_name = data.store_name;
        
        
        if (data.store_tagline !== undefined) updatePayload.store_tagline = data.store_tagline;
        
        
        if (data.support_email !== undefined) updatePayload.support_email = data.support_email;
        
        
        if (data.support_phone !== undefined) updatePayload.support_phone = data.support_phone;
        
        
        if (data.whatsapp_number !== undefined) updatePayload.whatsapp_number = data.whatsapp_number;
        
        
        if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
        
        
        if (data.timezone !== undefined) updatePayload.timezone = data.timezone;
        
        
        if (data.primary_color_hex !== undefined) updatePayload.primary_color_hex = data.primary_color_hex;
        
        
        if (data.secondary_color_hex !== undefined) updatePayload.secondary_color_hex = data.secondary_color_hex;
        
        
        if (data.maintenance_mode !== undefined) updatePayload.maintenance_mode = data.maintenance_mode;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

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

        return store_settings;
    }

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

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

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


        return store_settings;
    }

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

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

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

        await store_settings.destroy({
            transaction
        });

        return store_settings;
    }

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

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

        if (!store_settings) {
            return store_settings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.logo_images = await store_settings.getLogo_images({
            transaction
        });
        
        
        output.banner_images = await store_settings.getBanner_images({
            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_images',
      },

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

    ];

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

            
            if (filter.store_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'store_settings',
                        'store_name',
                        filter.store_name,
                    ),
                };
            }
            
            if (filter.store_tagline) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'store_settings',
                        'store_tagline',
                        filter.store_tagline,
                    ),
                };
            }
            
            if (filter.support_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'store_settings',
                        'support_email',
                        filter.support_email,
                    ),
                };
            }
            
            if (filter.support_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'store_settings',
                        'support_phone',
                        filter.support_phone,
                    ),
                };
            }
            
            if (filter.whatsapp_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'store_settings',
                        'whatsapp_number',
                        filter.whatsapp_number,
                    ),
                };
            }
            
            if (filter.currency_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'store_settings',
                        'currency_code',
                        filter.currency_code,
                    ),
                };
            }
            
            if (filter.timezone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'store_settings',
                        'timezone',
                        filter.timezone,
                    ),
                };
            }
            
            if (filter.primary_color_hex) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'store_settings',
                        'primary_color_hex',
                        filter.primary_color_hex,
                    ),
                };
            }
            
            if (filter.secondary_color_hex) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'store_settings',
                        'secondary_color_hex',
                        filter.secondary_color_hex,
                    ),
                };
            }
            

            
            

            

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

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




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

        const records = await db.store_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,
        }));
    }

    
};

