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

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

        const profile_styles = await db.profile_styles.create(
            {
                id: data.id || undefined,
        
        style_name: data.style_name
        ||
        null
            ,
            
        username_color_hex: data.username_color_hex
        ||
        null
            ,
            
        bio_font_family: data.bio_font_family
        ||
        null
            ,
            
        panel_order_json: data.panel_order_json
        ||
        null
            ,
            
        profile_layout: data.profile_layout
        ||
        null
            ,
            
        show_pronouns_badge: data.show_pronouns_badge
        ||
        false
        
            ,
            
        pronouns_text: data.pronouns_text
        ||
        null
            ,
            
        custom_css: data.custom_css
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

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

        return profile_styles;
    }
    

    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 profile_stylesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                style_name: item.style_name
            ||
            null
            ,
            
                username_color_hex: item.username_color_hex
            ||
            null
            ,
            
                bio_font_family: item.bio_font_family
            ||
            null
            ,
            
                panel_order_json: item.panel_order_json
            ||
            null
            ,
            
                profile_layout: item.profile_layout
            ||
            null
            ,
            
                show_pronouns_badge: item.show_pronouns_badge
            ||
            false
        
            ,
            
                pronouns_text: item.pronouns_text
            ||
            null
            ,
            
                custom_css: item.custom_css
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return profile_styles;
    }

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


        

        const updatePayload = {};
        
        if (data.style_name !== undefined) updatePayload.style_name = data.style_name;
        
        
        if (data.username_color_hex !== undefined) updatePayload.username_color_hex = data.username_color_hex;
        
        
        if (data.bio_font_family !== undefined) updatePayload.bio_font_family = data.bio_font_family;
        
        
        if (data.panel_order_json !== undefined) updatePayload.panel_order_json = data.panel_order_json;
        
        
        if (data.profile_layout !== undefined) updatePayload.profile_layout = data.profile_layout;
        
        
        if (data.show_pronouns_badge !== undefined) updatePayload.show_pronouns_badge = data.show_pronouns_badge;
        
        
        if (data.pronouns_text !== undefined) updatePayload.pronouns_text = data.pronouns_text;
        
        
        if (data.custom_css !== undefined) updatePayload.custom_css = data.custom_css;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

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

        return profile_styles;
    }

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

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

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


        return profile_styles;
    }

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

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

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

        await profile_styles.destroy({
            transaction
        });

        return profile_styles;
    }

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

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

        if (!profile_styles) {
            return profile_styles;
        }

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

        
        
        
        
        
        output.creator_profiles_profile_style = await profile_styles.getCreator_profiles_profile_style({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.owner_user = await profile_styles.getOwner_user({
            transaction
        });
        
        
        output.avatar_frame_images = await profile_styles.getAvatar_frame_images({
            transaction
        });
        
        
        output.banner_background_images = await profile_styles.getBanner_background_images({
            transaction
        });
        
        
        output.organizations = await profile_styles.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',
        
      },



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

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

    ];

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

            
            if (filter.style_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'profile_styles',
                        'style_name',
                        filter.style_name,
                    ),
                };
            }
            
            if (filter.username_color_hex) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'profile_styles',
                        'username_color_hex',
                        filter.username_color_hex,
                    ),
                };
            }
            
            if (filter.bio_font_family) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'profile_styles',
                        'bio_font_family',
                        filter.bio_font_family,
                    ),
                };
            }
            
            if (filter.panel_order_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'profile_styles',
                        'panel_order_json',
                        filter.panel_order_json,
                    ),
                };
            }
            
            if (filter.pronouns_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'profile_styles',
                        'pronouns_text',
                        filter.pronouns_text,
                    ),
                };
            }
            
            if (filter.custom_css) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'profile_styles',
                        'custom_css',
                        filter.custom_css,
                    ),
                };
            }
            

            
            

            

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

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


      

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

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

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

    
};

