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

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

        const quests = await db.quests.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        quest_type: data.quest_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        available_from: data.available_from
        ||
        null
            ,
            
        available_until: data.available_until
        ||
        null
            ,
            
        reward_money: data.reward_money
        ||
        null
            ,
            
        reward_reputation: data.reward_reputation
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await quests.setGiver_npc( data.giver_npc || null, {
            transaction,
        });
        
        await quests.setStart_location( data.start_location || null, {
            transaction,
        });
        
        await quests.setEnd_location( data.end_location || null, {
            transaction,
        });
        

        

        

        return quests;
    }
    

    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 questsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                quest_type: item.quest_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                available_from: item.available_from
            ||
            null
            ,
            
                available_until: item.available_until
            ||
            null
            ,
            
                reward_money: item.reward_money
            ||
            null
            ,
            
                reward_reputation: item.reward_reputation
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return quests;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.quest_type !== undefined) updatePayload.quest_type = data.quest_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.available_from !== undefined) updatePayload.available_from = data.available_from;
        
        
        if (data.available_until !== undefined) updatePayload.available_until = data.available_until;
        
        
        if (data.reward_money !== undefined) updatePayload.reward_money = data.reward_money;
        
        
        if (data.reward_reputation !== undefined) updatePayload.reward_reputation = data.reward_reputation;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.giver_npc !== undefined) {
            await quests.setGiver_npc(
              
              data.giver_npc,
              
              { transaction }
            );
        }
        
        if (data.start_location !== undefined) {
            await quests.setStart_location(
              
              data.start_location,
              
              { transaction }
            );
        }
        
        if (data.end_location !== undefined) {
            await quests.setEnd_location(
              
              data.end_location,
              
              { transaction }
            );
        }
        

        
        

        

        return quests;
    }

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

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

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


        return quests;
    }

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

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

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

        await quests.destroy({
            transaction
        });

        return quests;
    }

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

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

        if (!quests) {
            return quests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.quest_objectives_quest = await quests.getQuest_objectives_quest({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.giver_npc = await quests.getGiver_npc({
            transaction
        });
        
        
        output.start_location = await quests.getStart_location({
            transaction
        });
        
        
        output.end_location = await quests.getEnd_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.npcs,
        as: 'giver_npc',
        
        where: filter.giver_npc ? {
          [Op.or]: [
            { id: { [Op.in]: filter.giver_npc.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.giver_npc.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'quests',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'quests',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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


      

      

      



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

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

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

    
};

