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

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

        const avatar_customizations = await db.avatar_customizations.create(
            {
                id: data.id || undefined,
        
        profile_name: data.profile_name
        ||
        null
            ,
            
        base_color: data.base_color
        ||
        null
            ,
            
        custom_color_hex: data.custom_color_hex
        ||
        null
            ,
            
        face_style: data.face_style
        ||
        null
            ,
            
        pattern_style: data.pattern_style
        ||
        null
            ,
            
        pattern_color: data.pattern_color
        ||
        null
            ,
            
        pattern_custom_hex: data.pattern_custom_hex
        ||
        null
            ,
            
        hat_style: data.hat_style
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await avatar_customizations.setUser( data.user || null, {
            transaction,
        });
        

        

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

        return avatar_customizations;
    }
    

    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 avatar_customizationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                profile_name: item.profile_name
            ||
            null
            ,
            
                base_color: item.base_color
            ||
            null
            ,
            
                custom_color_hex: item.custom_color_hex
            ||
            null
            ,
            
                face_style: item.face_style
            ||
            null
            ,
            
                pattern_style: item.pattern_style
            ||
            null
            ,
            
                pattern_color: item.pattern_color
            ||
            null
            ,
            
                pattern_custom_hex: item.pattern_custom_hex
            ||
            null
            ,
            
                hat_style: item.hat_style
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return avatar_customizations;
    }

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

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


        

        const updatePayload = {};
        
        if (data.profile_name !== undefined) updatePayload.profile_name = data.profile_name;
        
        
        if (data.base_color !== undefined) updatePayload.base_color = data.base_color;
        
        
        if (data.custom_color_hex !== undefined) updatePayload.custom_color_hex = data.custom_color_hex;
        
        
        if (data.face_style !== undefined) updatePayload.face_style = data.face_style;
        
        
        if (data.pattern_style !== undefined) updatePayload.pattern_style = data.pattern_style;
        
        
        if (data.pattern_color !== undefined) updatePayload.pattern_color = data.pattern_color;
        
        
        if (data.pattern_custom_hex !== undefined) updatePayload.pattern_custom_hex = data.pattern_custom_hex;
        
        
        if (data.hat_style !== undefined) updatePayload.hat_style = data.hat_style;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await avatar_customizations.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

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

        return avatar_customizations;
    }

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

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

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


        return avatar_customizations;
    }

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

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

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

        await avatar_customizations.destroy({
            transaction
        });

        return avatar_customizations;
    }

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

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

        if (!avatar_customizations) {
            return avatar_customizations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.match_players_avatar_customization = await avatar_customizations.getMatch_players_avatar_customization({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await avatar_customizations.getUser({
            transaction
        });
        
        
        output.render_images = await avatar_customizations.getRender_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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.profile_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'avatar_customizations',
                        'profile_name',
                        filter.profile_name,
                    ),
                };
            }
            
            if (filter.custom_color_hex) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'avatar_customizations',
                        'custom_color_hex',
                        filter.custom_color_hex,
                    ),
                };
            }
            
            if (filter.pattern_custom_hex) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'avatar_customizations',
                        'pattern_custom_hex',
                        filter.pattern_custom_hex,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.base_color) {
                where = {
                    ...where,
                base_color: filter.base_color,
            };
            }
            
            if (filter.face_style) {
                where = {
                    ...where,
                face_style: filter.face_style,
            };
            }
            
            if (filter.pattern_style) {
                where = {
                    ...where,
                pattern_style: filter.pattern_style,
            };
            }
            
            if (filter.pattern_color) {
                where = {
                    ...where,
                pattern_color: filter.pattern_color,
            };
            }
            
            if (filter.hat_style) {
                where = {
                    ...where,
                hat_style: filter.hat_style,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      



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

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

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

    
};

