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

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

        const boxes = await db.boxes.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        box_type: data.box_type
        ||
        null
            ,
            
        price_yux: data.price_yux
        ||
        null
            ,
            
        is_available: data.is_available
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

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

        return boxes;
    }
    

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

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

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

        return boxes;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.box_type !== undefined) updatePayload.box_type = data.box_type;
        
        
        if (data.price_yux !== undefined) updatePayload.price_yux = data.price_yux;
        
        
        if (data.is_available !== undefined) updatePayload.is_available = data.is_available;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

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

        return boxes;
    }

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

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

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


        return boxes;
    }

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

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

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

        await boxes.destroy({
            transaction
        });

        return boxes;
    }

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

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

        if (!boxes) {
            return boxes;
        }

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

        
        
        
        
        
        
        
        
        output.box_items_box = await boxes.getBox_items_box({
            transaction
        });
        
        
        output.purchases_box = await boxes.getPurchases_box({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.daily_rewards_box = await boxes.getDaily_rewards_box({
            transaction
        });
        
        
        
        
        
        
        
        output.box_images = await boxes.getBox_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.file,
        as: 'box_images',
      },

    ];

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

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

            
            

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

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

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

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

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




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

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

    
};

