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

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

        const promo_codes = await db.promo_codes.create(
            {
                id: data.id || undefined,
        
        code: data.code
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        discount_type: data.discount_type
        ||
        null
            ,
            
        discount_value: data.discount_value
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        valid_from_at: data.valid_from_at
        ||
        null
            ,
            
        valid_to_at: data.valid_to_at
        ||
        null
            ,
            
        max_uses: data.max_uses
        ||
        null
            ,
            
        max_uses_per_guest: data.max_uses_per_guest
        ||
        null
            ,
            
        min_nights: data.min_nights
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await promo_codes.setHotel( data.hotel || null, {
            transaction,
        });
        

        

        

        return promo_codes;
    }
    

    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 promo_codesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                code: item.code
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                discount_type: item.discount_type
            ||
            null
            ,
            
                discount_value: item.discount_value
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                valid_from_at: item.valid_from_at
            ||
            null
            ,
            
                valid_to_at: item.valid_to_at
            ||
            null
            ,
            
                max_uses: item.max_uses
            ||
            null
            ,
            
                max_uses_per_guest: item.max_uses_per_guest
            ||
            null
            ,
            
                min_nights: item.min_nights
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return promo_codes;
    }

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

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


        

        const updatePayload = {};
        
        if (data.code !== undefined) updatePayload.code = data.code;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.discount_type !== undefined) updatePayload.discount_type = data.discount_type;
        
        
        if (data.discount_value !== undefined) updatePayload.discount_value = data.discount_value;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.valid_from_at !== undefined) updatePayload.valid_from_at = data.valid_from_at;
        
        
        if (data.valid_to_at !== undefined) updatePayload.valid_to_at = data.valid_to_at;
        
        
        if (data.max_uses !== undefined) updatePayload.max_uses = data.max_uses;
        
        
        if (data.max_uses_per_guest !== undefined) updatePayload.max_uses_per_guest = data.max_uses_per_guest;
        
        
        if (data.min_nights !== undefined) updatePayload.min_nights = data.min_nights;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.hotel !== undefined) {
            await promo_codes.setHotel(
              
              data.hotel,
              
              { transaction }
            );
        }
        

        
        

        

        return promo_codes;
    }

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

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

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


        return promo_codes;
    }

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

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

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

        await promo_codes.destroy({
            transaction
        });

        return promo_codes;
    }

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

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

        if (!promo_codes) {
            return promo_codes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.booking_discounts_promo_code = await promo_codes.getBooking_discounts_promo_code({
            transaction
        });
        
        
        
        
        
        
        
        output.hotel = await promo_codes.getHotel({
            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.hotels,
        as: 'hotel',
        
        where: filter.hotel ? {
          [Op.or]: [
            { id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.hotel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'promo_codes',
                        'code',
                        filter.code,
                    ),
                };
            }
            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'promo_codes',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'promo_codes',
                        '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.valid_from_atRange) {
                const [start, end] = filter.valid_from_atRange;

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    min_nights: {
                    ...where.min_nights,
                            [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.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      



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

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

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

    
};

