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

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

        const crafting_recipes = await db.crafting_recipes.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        recipe_type: data.recipe_type
        ||
        null
            ,
            
        output_quantity: data.output_quantity
        ||
        null
            ,
            
        craft_time_seconds: data.craft_time_seconds
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await crafting_recipes.setOutput_item( data.output_item || null, {
            transaction,
        });
        
        await crafting_recipes.setRequired_station_location( data.required_station_location || null, {
            transaction,
        });
        

        

        

        return crafting_recipes;
    }
    

    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 crafting_recipesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                recipe_type: item.recipe_type
            ||
            null
            ,
            
                output_quantity: item.output_quantity
            ||
            null
            ,
            
                craft_time_seconds: item.craft_time_seconds
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return crafting_recipes;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.recipe_type !== undefined) updatePayload.recipe_type = data.recipe_type;
        
        
        if (data.output_quantity !== undefined) updatePayload.output_quantity = data.output_quantity;
        
        
        if (data.craft_time_seconds !== undefined) updatePayload.craft_time_seconds = data.craft_time_seconds;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.output_item !== undefined) {
            await crafting_recipes.setOutput_item(
              
              data.output_item,
              
              { transaction }
            );
        }
        
        if (data.required_station_location !== undefined) {
            await crafting_recipes.setRequired_station_location(
              
              data.required_station_location,
              
              { transaction }
            );
        }
        

        
        

        

        return crafting_recipes;
    }

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

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

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


        return crafting_recipes;
    }

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

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

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

        await crafting_recipes.destroy({
            transaction
        });

        return crafting_recipes;
    }

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

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

        if (!crafting_recipes) {
            return crafting_recipes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.recipe_ingredients_recipe = await crafting_recipes.getRecipe_ingredients_recipe({
            transaction
        });
        
        
        
        
        
        
        
        
        output.output_item = await crafting_recipes.getOutput_item({
            transaction
        });
        
        
        output.required_station_location = await crafting_recipes.getRequired_station_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.items,
        as: 'output_item',
        
        where: filter.output_item ? {
          [Op.or]: [
            { id: { [Op.in]: filter.output_item.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.output_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

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

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

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

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

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

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

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


      

      



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

        const records = await db.crafting_recipes.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,
        }));
    }

    
};

