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

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

        const stripe_events = await db.stripe_events.create(
            {
                id: data.id || undefined,
        
        event_ref: data.event_ref
        ||
        null
            ,
            
        event_type: data.event_type
        ||
        null
            ,
            
        received_at: data.received_at
        ||
        null
            ,
            
        processed: data.processed
        ||
        false
        
            ,
            
        processing_notes: data.processing_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await stripe_events.setUser( data.user || null, {
            transaction,
        });
        
        await stripe_events.setMembership( data.membership || null, {
            transaction,
        });
        

        

        

        return stripe_events;
    }
    

    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 stripe_eventsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                event_ref: item.event_ref
            ||
            null
            ,
            
                event_type: item.event_type
            ||
            null
            ,
            
                received_at: item.received_at
            ||
            null
            ,
            
                processed: item.processed
            ||
            false
        
            ,
            
                processing_notes: item.processing_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return stripe_events;
    }

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

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


        

        const updatePayload = {};
        
        if (data.event_ref !== undefined) updatePayload.event_ref = data.event_ref;
        
        
        if (data.event_type !== undefined) updatePayload.event_type = data.event_type;
        
        
        if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
        
        
        if (data.processed !== undefined) updatePayload.processed = data.processed;
        
        
        if (data.processing_notes !== undefined) updatePayload.processing_notes = data.processing_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await stripe_events.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.membership !== undefined) {
            await stripe_events.setMembership(
              
              data.membership,
              
              { transaction }
            );
        }
        

        
        

        

        return stripe_events;
    }

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

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

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


        return stripe_events;
    }

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

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

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

        await stripe_events.destroy({
            transaction
        });

        return stripe_events;
    }

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

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

        if (!stripe_events) {
            return stripe_events;
        }

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

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



    ];

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

            
            if (filter.event_ref) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stripe_events',
                        'event_ref',
                        filter.event_ref,
                    ),
                };
            }
            
            if (filter.processing_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stripe_events',
                        'processing_notes',
                        filter.processing_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      



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

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

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

    
};

