
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
            ,
            
        discount_type: data.discount_type
        ||
        null
            ,
            
        discount_value: data.discount_value
        ||
        null
            ,
            
        min_subtotal: data.min_subtotal
        ||
        null
            ,
            
        start_at: data.start_at
        ||
        null
            ,
            
        end_at: data.end_at
        ||
        null
            ,
            
        usage_limit: data.usage_limit
        ||
        null
            ,
            
        usage_count: data.usage_count
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await promo_codes.setCompany( data.company || null, {
            transaction,
        });
        
        await promo_codes.setOrganizations( data.organizations || 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
            ,
            
                discount_type: item.discount_type
            ||
            null
            ,
            
                discount_value: item.discount_value
            ||
            null
            ,
            
                min_subtotal: item.min_subtotal
            ||
            null
            ,
            
                start_at: item.start_at
            ||
            null
            ,
            
                end_at: item.end_at
            ||
            null
            ,
            
                usage_limit: item.usage_limit
            ||
            null
            ,
            
                usage_count: item.usage_count
            ||
            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 globalAccess = currentUser.app_role?.globalAccess;

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


        

        const updatePayload = {};
        
        if (data.code !== undefined) updatePayload.code = data.code;
        
        
        if (data.discount_type !== undefined) updatePayload.discount_type = data.discount_type;
        
        
        if (data.discount_value !== undefined) updatePayload.discount_value = data.discount_value;
        
        
        if (data.min_subtotal !== undefined) updatePayload.min_subtotal = data.min_subtotal;
        
        
        if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
        
        
        if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
        
        
        if (data.usage_limit !== undefined) updatePayload.usage_limit = data.usage_limit;
        
        
        if (data.usage_count !== undefined) updatePayload.usage_count = data.usage_count;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await promo_codes.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await promo_codes.setOrganizations(
              
              data.organizations,
              
              { 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.bookings_promo_code = await promo_codes.getBookings_promo_code({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await promo_codes.getCompany({
            transaction
        });
        
        
        output.organizations = await promo_codes.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    usage_count: {
                    ...where.usage_count,
                            [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.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        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,
        }));
    }

    
};

