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

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

        const purchases = await db.purchases.create(
            {
                id: data.id || undefined,
        
        purchase_type: data.purchase_type
        ||
        null
            ,
            
        amount_yux: data.amount_yux
        ||
        null
            ,
            
        purchased_at: data.purchased_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await purchases.setUser( data.user || null, {
            transaction,
        });
        
        await purchases.setBox( data.box || null, {
            transaction,
        });
        
        await purchases.setCosmetic( data.cosmetic || null, {
            transaction,
        });
        

        

        

        return purchases;
    }
    

    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 purchasesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                purchase_type: item.purchase_type
            ||
            null
            ,
            
                amount_yux: item.amount_yux
            ||
            null
            ,
            
                purchased_at: item.purchased_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return purchases;
    }

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

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


        

        const updatePayload = {};
        
        if (data.purchase_type !== undefined) updatePayload.purchase_type = data.purchase_type;
        
        
        if (data.amount_yux !== undefined) updatePayload.amount_yux = data.amount_yux;
        
        
        if (data.purchased_at !== undefined) updatePayload.purchased_at = data.purchased_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await purchases.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.box !== undefined) {
            await purchases.setBox(
              
              data.box,
              
              { transaction }
            );
        }
        
        if (data.cosmetic !== undefined) {
            await purchases.setCosmetic(
              
              data.cosmetic,
              
              { transaction }
            );
        }
        

        
        

        

        return purchases;
    }

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

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

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


        return purchases;
    }

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

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

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

        await purchases.destroy({
            transaction
        });

        return purchases;
    }

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

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

        if (!purchases) {
            return purchases;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await purchases.getUser({
            transaction
        });
        
        
        output.box = await purchases.getBox({
            transaction
        });
        
        
        output.cosmetic = await purchases.getCosmetic({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            

            
            

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

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

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

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

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

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

            
            if (filter.purchase_type) {
                where = {
                    ...where,
                purchase_type: filter.purchase_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.purchases.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(
                        'purchases',
                        'purchase_type',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

