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

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

        const public_profiles = await db.public_profiles.create(
            {
                id: data.id || undefined,
        
        display_name: data.display_name
        ||
        null
            ,
            
        headline: data.headline
        ||
        null
            ,
            
        bio: data.bio
        ||
        null
            ,
            
        location: data.location
        ||
        null
            ,
            
        public_slug: data.public_slug
        ||
        null
            ,
            
        is_public: data.is_public
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        
        await public_profiles.setTrophies(data.trophies || [], {
            transaction,
        });
        
        await public_profiles.setPublic_artifacts(data.public_artifacts || [], {
            transaction,
        });
        

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

        return public_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 public_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                display_name: item.display_name
            ||
            null
            ,
            
                headline: item.headline
            ||
            null
            ,
            
                bio: item.bio
            ||
            null
            ,
            
                location: item.location
            ||
            null
            ,
            
                public_slug: item.public_slug
            ||
            null
            ,
            
                is_public: item.is_public
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return public_profiles;
    }

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

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


        

        const updatePayload = {};
        
        if (data.display_name !== undefined) updatePayload.display_name = data.display_name;
        
        
        if (data.headline !== undefined) updatePayload.headline = data.headline;
        
        
        if (data.bio !== undefined) updatePayload.bio = data.bio;
        
        
        if (data.location !== undefined) updatePayload.location = data.location;
        
        
        if (data.public_slug !== undefined) updatePayload.public_slug = data.public_slug;
        
        
        if (data.is_public !== undefined) updatePayload.is_public = data.is_public;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        
        if (data.trophies !== undefined) {
            await public_profiles.setTrophies(data.trophies, { transaction });
        }
        
        if (data.public_artifacts !== undefined) {
            await public_profiles.setPublic_artifacts(data.public_artifacts, { transaction });
        }
        

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

        return public_profiles;
    }

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

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

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


        return public_profiles;
    }

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

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

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

        await public_profiles.destroy({
            transaction
        });

        return public_profiles;
    }

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

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

        if (!public_profiles) {
            return public_profiles;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await public_profiles.getUser({
            transaction
        });
        
        
        output.avatar_images = await public_profiles.getAvatar_images({
            transaction
        });
        
        
        output.trophies = await public_profiles.getTrophies({
            transaction
        });
        
        
        output.public_artifacts = await public_profiles.getPublic_artifacts({
            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.trophies,
        as: 'trophies',
        required: false,
      },

      {
        model: db.artifacts,
        as: 'public_artifacts',
        required: false,
      },


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

    ];

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

            
            if (filter.display_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'public_profiles',
                        'display_name',
                        filter.display_name,
                    ),
                };
            }
            
            if (filter.headline) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'public_profiles',
                        'headline',
                        filter.headline,
                    ),
                };
            }
            
            if (filter.bio) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'public_profiles',
                        'bio',
                        filter.bio,
                    ),
                };
            }
            
            if (filter.location) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'public_profiles',
                        'location',
                        filter.location,
                    ),
                };
            }
            
            if (filter.public_slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'public_profiles',
                        'public_slug',
                        filter.public_slug,
                    ),
                };
            }
            

            
            

            

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

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


      


      if (filter.trophies) {
        const searchTerms = filter.trophies.split('|');

        include = [
          {
            model: db.trophies,
            as: 'trophies_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  trophy_name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.public_artifacts) {
        const searchTerms = filter.public_artifacts.split('|');

        include = [
          {
            model: db.artifacts,
            as: 'public_artifacts_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  title: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


            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.public_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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'public_profiles',
                        'display_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

