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

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

        const npc_relationships = await db.npc_relationships.create(
            {
                id: data.id || undefined,
        
        relationship_type: data.relationship_type
        ||
        null
            ,
            
        friendship_points: data.friendship_points
        ||
        null
            ,
            
        trust_points: data.trust_points
        ||
        null
            ,
            
        last_interaction_at: data.last_interaction_at
        ||
        null
            ,
            
        is_unlocked: data.is_unlocked
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await npc_relationships.setPlayer_profile( data.player_profile || null, {
            transaction,
        });
        
        await npc_relationships.setNpc( data.npc || null, {
            transaction,
        });
        

        

        

        return npc_relationships;
    }
    

    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 npc_relationshipsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                relationship_type: item.relationship_type
            ||
            null
            ,
            
                friendship_points: item.friendship_points
            ||
            null
            ,
            
                trust_points: item.trust_points
            ||
            null
            ,
            
                last_interaction_at: item.last_interaction_at
            ||
            null
            ,
            
                is_unlocked: item.is_unlocked
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return npc_relationships;
    }

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

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


        

        const updatePayload = {};
        
        if (data.relationship_type !== undefined) updatePayload.relationship_type = data.relationship_type;
        
        
        if (data.friendship_points !== undefined) updatePayload.friendship_points = data.friendship_points;
        
        
        if (data.trust_points !== undefined) updatePayload.trust_points = data.trust_points;
        
        
        if (data.last_interaction_at !== undefined) updatePayload.last_interaction_at = data.last_interaction_at;
        
        
        if (data.is_unlocked !== undefined) updatePayload.is_unlocked = data.is_unlocked;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.player_profile !== undefined) {
            await npc_relationships.setPlayer_profile(
              
              data.player_profile,
              
              { transaction }
            );
        }
        
        if (data.npc !== undefined) {
            await npc_relationships.setNpc(
              
              data.npc,
              
              { transaction }
            );
        }
        

        
        

        

        return npc_relationships;
    }

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

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

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


        return npc_relationships;
    }

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

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

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

        await npc_relationships.destroy({
            transaction
        });

        return npc_relationships;
    }

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

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

        if (!npc_relationships) {
            return npc_relationships;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.player_profile = await npc_relationships.getPlayer_profile({
            transaction
        });
        
        
        output.npc = await npc_relationships.getNpc({
            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.player_profiles,
        as: 'player_profile',
        
        where: filter.player_profile ? {
          [Op.or]: [
            { id: { [Op.in]: filter.player_profile.split('|').map(term => Utils.uuid(term)) } },
            {
              first_name: {
                [Op.or]: filter.player_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.npcs,
        as: 'npc',
        
        where: filter.npc ? {
          [Op.or]: [
            { id: { [Op.in]: filter.npc.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.npc.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    friendship_points: {
                    ...where.friendship_points,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.trust_pointsRange) {
                const [start, end] = filter.trust_pointsRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    trust_points: {
                    ...where.trust_points,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.last_interaction_atRange) {
                const [start, end] = filter.last_interaction_atRange;

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

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

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

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


      

      



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

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

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

    
};

