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

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

        const quest_objectives = await db.quest_objectives.create(
            {
                id: data.id || undefined,
        
        objective_type: data.objective_type
        ||
        null
            ,
            
        target_quantity: data.target_quantity
        ||
        null
            ,
            
        sequence_order: data.sequence_order
        ||
        null
            ,
            
        is_optional: data.is_optional
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await quest_objectives.setQuest( data.quest || null, {
            transaction,
        });
        
        await quest_objectives.setTarget_item( data.target_item || null, {
            transaction,
        });
        
        await quest_objectives.setTarget_npc( data.target_npc || null, {
            transaction,
        });
        
        await quest_objectives.setTarget_location( data.target_location || null, {
            transaction,
        });
        

        

        

        return quest_objectives;
    }
    

    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 quest_objectivesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                objective_type: item.objective_type
            ||
            null
            ,
            
                target_quantity: item.target_quantity
            ||
            null
            ,
            
                sequence_order: item.sequence_order
            ||
            null
            ,
            
                is_optional: item.is_optional
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return quest_objectives;
    }

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

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


        

        const updatePayload = {};
        
        if (data.objective_type !== undefined) updatePayload.objective_type = data.objective_type;
        
        
        if (data.target_quantity !== undefined) updatePayload.target_quantity = data.target_quantity;
        
        
        if (data.sequence_order !== undefined) updatePayload.sequence_order = data.sequence_order;
        
        
        if (data.is_optional !== undefined) updatePayload.is_optional = data.is_optional;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.quest !== undefined) {
            await quest_objectives.setQuest(
              
              data.quest,
              
              { transaction }
            );
        }
        
        if (data.target_item !== undefined) {
            await quest_objectives.setTarget_item(
              
              data.target_item,
              
              { transaction }
            );
        }
        
        if (data.target_npc !== undefined) {
            await quest_objectives.setTarget_npc(
              
              data.target_npc,
              
              { transaction }
            );
        }
        
        if (data.target_location !== undefined) {
            await quest_objectives.setTarget_location(
              
              data.target_location,
              
              { transaction }
            );
        }
        

        
        

        

        return quest_objectives;
    }

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

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

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


        return quest_objectives;
    }

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

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

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

        await quest_objectives.destroy({
            transaction
        });

        return quest_objectives;
    }

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

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

        if (!quest_objectives) {
            return quest_objectives;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.quest = await quest_objectives.getQuest({
            transaction
        });
        
        
        output.target_item = await quest_objectives.getTarget_item({
            transaction
        });
        
        
        output.target_npc = await quest_objectives.getTarget_npc({
            transaction
        });
        
        
        output.target_location = await quest_objectives.getTarget_location({
            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.quests,
        as: 'quest',
        
        where: filter.quest ? {
          [Op.or]: [
            { id: { [Op.in]: filter.quest.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.quest.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



    ];

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

            

            
            

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

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

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

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

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

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

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


      

      

      

      



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

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

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

    
};

