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

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

        const booking_discounts = await db.booking_discounts.create(
            {
                id: data.id || undefined,
        
        discount_type: data.discount_type
        ||
        null
            ,
            
        discount_value: data.discount_value
        ||
        null
            ,
            
        discount_amount: data.discount_amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await booking_discounts.setBooking( data.booking || null, {
            transaction,
        });
        
        await booking_discounts.setPromo_code( data.promo_code || null, {
            transaction,
        });
        

        

        

        return booking_discounts;
    }
    

    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 booking_discountsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                discount_type: item.discount_type
            ||
            null
            ,
            
                discount_value: item.discount_value
            ||
            null
            ,
            
                discount_amount: item.discount_amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return booking_discounts;
    }

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

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


        

        const updatePayload = {};
        
        if (data.discount_type !== undefined) updatePayload.discount_type = data.discount_type;
        
        
        if (data.discount_value !== undefined) updatePayload.discount_value = data.discount_value;
        
        
        if (data.discount_amount !== undefined) updatePayload.discount_amount = data.discount_amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.booking !== undefined) {
            await booking_discounts.setBooking(
              
              data.booking,
              
              { transaction }
            );
        }
        
        if (data.promo_code !== undefined) {
            await booking_discounts.setPromo_code(
              
              data.promo_code,
              
              { transaction }
            );
        }
        

        
        

        

        return booking_discounts;
    }

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

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

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


        return booking_discounts;
    }

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

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

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

        await booking_discounts.destroy({
            transaction
        });

        return booking_discounts;
    }

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

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

        if (!booking_discounts) {
            return booking_discounts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.booking = await booking_discounts.getBooking({
            transaction
        });
        
        
        output.promo_code = await booking_discounts.getPromo_code({
            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.bookings,
        as: 'booking',
        
        where: filter.booking ? {
          [Op.or]: [
            { id: { [Op.in]: filter.booking.split('|').map(term => Utils.uuid(term)) } },
            {
              booking_code: {
                [Op.or]: filter.booking.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

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

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

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

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

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

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

            
            if (filter.discount_type) {
                where = {
                    ...where,
                discount_type: filter.discount_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.booking_discounts.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(
                        'booking_discounts',
                        'discount_type',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

