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

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

        const theme_profiles = await db.theme_profiles.create(
            {
                id: data.id || undefined,
        
        mode: data.mode
        ||
        null
            ,
            
        theme_name: data.theme_name
        ||
        null
            ,
            
        primary_color_hex: data.primary_color_hex
        ||
        null
            ,
            
        accent_color_hex: data.accent_color_hex
        ||
        null
            ,
            
        neon_glow_color_hex: data.neon_glow_color_hex
        ||
        null
            ,
            
        rgb_cycle_enabled: data.rgb_cycle_enabled
        ||
        false
        
            ,
            
        rgb_cycle_speed: data.rgb_cycle_speed
        ||
        null
            ,
            
        holiday_palette: data.holiday_palette
        ||
        null
            ,
            
        adult_palette_enabled: data.adult_palette_enabled
        ||
        false
        
            ,
            
        adult_primary_color_hex: data.adult_primary_color_hex
        ||
        null
            ,
            
        adult_accent_color_hex: data.adult_accent_color_hex
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await theme_profiles.setOwner_user( data.owner_user || null, {
            transaction,
        });
        
        await theme_profiles.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return theme_profiles;
    }
    

    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 theme_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                mode: item.mode
            ||
            null
            ,
            
                theme_name: item.theme_name
            ||
            null
            ,
            
                primary_color_hex: item.primary_color_hex
            ||
            null
            ,
            
                accent_color_hex: item.accent_color_hex
            ||
            null
            ,
            
                neon_glow_color_hex: item.neon_glow_color_hex
            ||
            null
            ,
            
                rgb_cycle_enabled: item.rgb_cycle_enabled
            ||
            false
        
            ,
            
                rgb_cycle_speed: item.rgb_cycle_speed
            ||
            null
            ,
            
                holiday_palette: item.holiday_palette
            ||
            null
            ,
            
                adult_palette_enabled: item.adult_palette_enabled
            ||
            false
        
            ,
            
                adult_primary_color_hex: item.adult_primary_color_hex
            ||
            null
            ,
            
                adult_accent_color_hex: item.adult_accent_color_hex
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return theme_profiles;
    }

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


        

        const updatePayload = {};
        
        if (data.mode !== undefined) updatePayload.mode = data.mode;
        
        
        if (data.theme_name !== undefined) updatePayload.theme_name = data.theme_name;
        
        
        if (data.primary_color_hex !== undefined) updatePayload.primary_color_hex = data.primary_color_hex;
        
        
        if (data.accent_color_hex !== undefined) updatePayload.accent_color_hex = data.accent_color_hex;
        
        
        if (data.neon_glow_color_hex !== undefined) updatePayload.neon_glow_color_hex = data.neon_glow_color_hex;
        
        
        if (data.rgb_cycle_enabled !== undefined) updatePayload.rgb_cycle_enabled = data.rgb_cycle_enabled;
        
        
        if (data.rgb_cycle_speed !== undefined) updatePayload.rgb_cycle_speed = data.rgb_cycle_speed;
        
        
        if (data.holiday_palette !== undefined) updatePayload.holiday_palette = data.holiday_palette;
        
        
        if (data.adult_palette_enabled !== undefined) updatePayload.adult_palette_enabled = data.adult_palette_enabled;
        
        
        if (data.adult_primary_color_hex !== undefined) updatePayload.adult_primary_color_hex = data.adult_primary_color_hex;
        
        
        if (data.adult_accent_color_hex !== undefined) updatePayload.adult_accent_color_hex = data.adult_accent_color_hex;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.owner_user !== undefined) {
            await theme_profiles.setOwner_user(
              
              data.owner_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await theme_profiles.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return theme_profiles;
    }

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

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

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


        return theme_profiles;
    }

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

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

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

        await theme_profiles.destroy({
            transaction
        });

        return theme_profiles;
    }

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

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

        if (!theme_profiles) {
            return theme_profiles;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.owner_user = await theme_profiles.getOwner_user({
            transaction
        });
        
        
        output.organizations = await theme_profiles.getOrganizations({
            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.users,
        as: 'owner_user',
        
        where: filter.owner_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.owner_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.theme_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'theme_profiles',
                        'theme_name',
                        filter.theme_name,
                    ),
                };
            }
            
            if (filter.primary_color_hex) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'theme_profiles',
                        'primary_color_hex',
                        filter.primary_color_hex,
                    ),
                };
            }
            
            if (filter.accent_color_hex) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'theme_profiles',
                        'accent_color_hex',
                        filter.accent_color_hex,
                    ),
                };
            }
            
            if (filter.neon_glow_color_hex) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'theme_profiles',
                        'neon_glow_color_hex',
                        filter.neon_glow_color_hex,
                    ),
                };
            }
            
            if (filter.adult_primary_color_hex) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'theme_profiles',
                        'adult_primary_color_hex',
                        filter.adult_primary_color_hex,
                    ),
                };
            }
            
            if (filter.adult_accent_color_hex) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'theme_profiles',
                        'adult_accent_color_hex',
                        filter.adult_accent_color_hex,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.mode) {
                where = {
                    ...where,
                mode: filter.mode,
            };
            }
            
            if (filter.rgb_cycle_enabled) {
                where = {
                    ...where,
                rgb_cycle_enabled: filter.rgb_cycle_enabled,
            };
            }
            
            if (filter.holiday_palette) {
                where = {
                    ...where,
                holiday_palette: filter.holiday_palette,
            };
            }
            
            if (filter.adult_palette_enabled) {
                where = {
                    ...where,
                adult_palette_enabled: filter.adult_palette_enabled,
            };
            }
            


      

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

        where = {
          ...where,
          organizationsId: {[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.theme_profiles.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(
                        'theme_profiles',
                        'theme_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

