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

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

        const items = await db.items.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        item_type: data.item_type
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        base_price: data.base_price
        ||
        null
            ,
            
        weight: data.weight
        ||
        null
            ,
            
        is_stackable: data.is_stackable
        ||
        false
        
            ,
            
        max_stack_size: data.max_stack_size
        ||
        null
            ,
            
        is_perishable: data.is_perishable
        ||
        false
        
            ,
            
        shelf_life_days: data.shelf_life_days
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await items.setCategory( data.category || null, {
            transaction,
        });
        

        

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

        return items;
    }
    

    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 itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                item_type: item.item_type
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                base_price: item.base_price
            ||
            null
            ,
            
                weight: item.weight
            ||
            null
            ,
            
                is_stackable: item.is_stackable
            ||
            false
        
            ,
            
                max_stack_size: item.max_stack_size
            ||
            null
            ,
            
                is_perishable: item.is_perishable
            ||
            false
        
            ,
            
                shelf_life_days: item.shelf_life_days
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.item_type !== undefined) updatePayload.item_type = data.item_type;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.base_price !== undefined) updatePayload.base_price = data.base_price;
        
        
        if (data.weight !== undefined) updatePayload.weight = data.weight;
        
        
        if (data.is_stackable !== undefined) updatePayload.is_stackable = data.is_stackable;
        
        
        if (data.max_stack_size !== undefined) updatePayload.max_stack_size = data.max_stack_size;
        
        
        if (data.is_perishable !== undefined) updatePayload.is_perishable = data.is_perishable;
        
        
        if (data.shelf_life_days !== undefined) updatePayload.shelf_life_days = data.shelf_life_days;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.category !== undefined) {
            await items.setCategory(
              
              data.category,
              
              { transaction }
            );
        }
        

        
        

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

        return items;
    }

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

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

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


        return items;
    }

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

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

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

        await items.destroy({
            transaction
        });

        return items;
    }

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

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

        if (!items) {
            return items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.quest_objectives_target_item = await items.getQuest_objectives_target_item({
            transaction
        });
        
        
        
        
        
        output.store_products_item = await items.getStore_products_item({
            transaction
        });
        
        
        
        
        output.purchase_order_lines_item = await items.getPurchase_order_lines_item({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.price_modifiers_item = await items.getPrice_modifiers_item({
            transaction
        });
        
        
        output.crops_seed_item = await items.getCrops_seed_item({
            transaction
        });
        
        output.crops_harvest_item = await items.getCrops_harvest_item({
            transaction
        });
        
        
        
        
        output.fish_species_item = await items.getFish_species_item({
            transaction
        });
        
        
        
        
        output.crafting_recipes_output_item = await items.getCrafting_recipes_output_item({
            transaction
        });
        
        
        output.recipe_ingredients_item = await items.getRecipe_ingredients_item({
            transaction
        });
        
        
        
        
        
        
        
        
        output.category = await items.getCategory({
            transaction
        });
        
        
        output.item_images = await items.getItem_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.item_categories,
        as: 'category',
        
        where: filter.category ? {
          [Op.or]: [
            { id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.item_type) {
                where = {
                    ...where,
                item_type: filter.item_type,
            };
            }
            
            if (filter.is_stackable) {
                where = {
                    ...where,
                is_stackable: filter.is_stackable,
            };
            }
            
            if (filter.is_perishable) {
                where = {
                    ...where,
                is_perishable: filter.is_perishable,
            };
            }
            


      



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

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

    
};

