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

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

        const npcs = await db.npcs.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        age: data.age
        ||
        null
            ,
            
        profession: data.profession
        ||
        null
            ,
            
        personality: data.personality
        ||
        null
            ,
            
        bio: data.bio
        ||
        null
            ,
            
        emotion_state: data.emotion_state
        ||
        null
            ,
            
        is_main_character: data.is_main_character
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await npcs.setHome_location( data.home_location || null, {
            transaction,
        });
        
        await npcs.setWork_location( data.work_location || null, {
            transaction,
        });
        

        

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

        return npcs;
    }
    

    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 npcsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                age: item.age
            ||
            null
            ,
            
                profession: item.profession
            ||
            null
            ,
            
                personality: item.personality
            ||
            null
            ,
            
                bio: item.bio
            ||
            null
            ,
            
                emotion_state: item.emotion_state
            ||
            null
            ,
            
                is_main_character: item.is_main_character
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return npcs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.age !== undefined) updatePayload.age = data.age;
        
        
        if (data.profession !== undefined) updatePayload.profession = data.profession;
        
        
        if (data.personality !== undefined) updatePayload.personality = data.personality;
        
        
        if (data.bio !== undefined) updatePayload.bio = data.bio;
        
        
        if (data.emotion_state !== undefined) updatePayload.emotion_state = data.emotion_state;
        
        
        if (data.is_main_character !== undefined) updatePayload.is_main_character = data.is_main_character;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.home_location !== undefined) {
            await npcs.setHome_location(
              
              data.home_location,
              
              { transaction }
            );
        }
        
        if (data.work_location !== undefined) {
            await npcs.setWork_location(
              
              data.work_location,
              
              { transaction }
            );
        }
        

        
        

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

        return npcs;
    }

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

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

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


        return npcs;
    }

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

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

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

        await npcs.destroy({
            transaction
        });

        return npcs;
    }

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

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

        if (!npcs) {
            return npcs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.family_memberships_npc = await npcs.getFamily_memberships_npc({
            transaction
        });
        
        
        output.npc_relationships_npc = await npcs.getNpc_relationships_npc({
            transaction
        });
        
        
        
        output.dialogue_lines_npc = await npcs.getDialogue_lines_npc({
            transaction
        });
        
        
        output.quests_giver_npc = await npcs.getQuests_giver_npc({
            transaction
        });
        
        
        output.quest_objectives_target_npc = await npcs.getQuest_objectives_target_npc({
            transaction
        });
        
        
        
        output.employees_npc = await npcs.getEmployees_npc({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.sales_transactions_customer_npc = await npcs.getSales_transactions_customer_npc({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.festival_attendance_npc = await npcs.getFestival_attendance_npc({
            transaction
        });
        
        
        
        
        output.home_location = await npcs.getHome_location({
            transaction
        });
        
        
        output.work_location = await npcs.getWork_location({
            transaction
        });
        
        
        output.portrait_images = await npcs.getPortrait_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.locations,
        as: 'home_location',
        
        where: filter.home_location ? {
          [Op.or]: [
            { id: { [Op.in]: filter.home_location.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.home_location.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'npcs',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.bio) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'npcs',
                        'bio',
                        filter.bio,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.profession) {
                where = {
                    ...where,
                profession: filter.profession,
            };
            }
            
            if (filter.personality) {
                where = {
                    ...where,
                personality: filter.personality,
            };
            }
            
            if (filter.emotion_state) {
                where = {
                    ...where,
                emotion_state: filter.emotion_state,
            };
            }
            
            if (filter.is_main_character) {
                where = {
                    ...where,
                is_main_character: filter.is_main_character,
            };
            }
            


      

      



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

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

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

    
};

