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

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

        const product_purchases = await db.product_purchases.create(
            {
                id: data.id || undefined,
        
        purchased_at: data.purchased_at
        ||
        null
            ,
            
        price_supercharged: data.price_supercharged
        ||
        null
            ,
            
        access_status: data.access_status
        ||
        null
            ,
            
        access_expires_at: data.access_expires_at
        ||
        null
            ,
            
        note: data.note
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await product_purchases.setUser( data.user || null, {
            transaction,
        });
        
        await product_purchases.setProduct( data.product || null, {
            transaction,
        });
        

        

        

        return product_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 product_purchasesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                purchased_at: item.purchased_at
            ||
            null
            ,
            
                price_supercharged: item.price_supercharged
            ||
            null
            ,
            
                access_status: item.access_status
            ||
            null
            ,
            
                access_expires_at: item.access_expires_at
            ||
            null
            ,
            
                note: item.note
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return product_purchases;
    }

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

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


        

        const updatePayload = {};
        
        if (data.purchased_at !== undefined) updatePayload.purchased_at = data.purchased_at;
        
        
        if (data.price_supercharged !== undefined) updatePayload.price_supercharged = data.price_supercharged;
        
        
        if (data.access_status !== undefined) updatePayload.access_status = data.access_status;
        
        
        if (data.access_expires_at !== undefined) updatePayload.access_expires_at = data.access_expires_at;
        
        
        if (data.note !== undefined) updatePayload.note = data.note;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await product_purchases.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.product !== undefined) {
            await product_purchases.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        

        
        

        

        return product_purchases;
    }

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

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

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


        return product_purchases;
    }

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

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

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

        await product_purchases.destroy({
            transaction
        });

        return product_purchases;
    }

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

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

        if (!product_purchases) {
            return product_purchases;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await product_purchases.getUser({
            transaction
        });
        
        
        output.product = await product_purchases.getProduct({
            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.products,
        as: 'product',
        
        where: filter.product ? {
          [Op.or]: [
            { id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'product_purchases',
                        'note',
                        filter.note,
                    ),
                };
            }
            

            
            

            
            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.price_superchargedRange) {
                const [start, end] = filter.price_superchargedRange;

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

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

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

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

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

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


      

      



            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.product_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(
                        'product_purchases',
                        'access_status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

