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

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

        const shop_items = await db.shop_items.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        cost_doodlecoins: data.cost_doodlecoins
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

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

        return shop_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 shop_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                cost_doodlecoins: item.cost_doodlecoins
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return shop_items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.cost_doodlecoins !== undefined) updatePayload.cost_doodlecoins = data.cost_doodlecoins;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

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

        return shop_items;
    }

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

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

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


        return shop_items;
    }

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

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

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

        await shop_items.destroy({
            transaction
        });

        return shop_items;
    }

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

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

        if (!shop_items) {
            return shop_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.item_redemptions_shop_item = await shop_items.getItem_redemptions_shop_item({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.thumbnail_image = await shop_items.getThumbnail_image({
            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.file,
        as: 'thumbnail_image',
      },

    ];

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

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

            
            

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

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

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

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

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




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

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

    
};

