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

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

        const license_activations = await db.license_activations.create(
            {
                id: data.id || undefined,
        
        activated_at: data.activated_at
        ||
        null
            ,
            
        activated_by: data.activated_by
        ||
        null
            ,
            
        client_info: data.client_info
        ||
        null
            ,
            
        activation_token: data.activation_token
        ||
        null
            ,
            
        result: data.result
        ||
        null
            ,
            
        failure_reason: data.failure_reason
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await license_activations.setLicense_key( data.license_key || null, {
            transaction,
        });
        

        

        

        return license_activations;
    }
    

    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 license_activationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                activated_at: item.activated_at
            ||
            null
            ,
            
                activated_by: item.activated_by
            ||
            null
            ,
            
                client_info: item.client_info
            ||
            null
            ,
            
                activation_token: item.activation_token
            ||
            null
            ,
            
                result: item.result
            ||
            null
            ,
            
                failure_reason: item.failure_reason
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return license_activations;
    }

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

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


        

        const updatePayload = {};
        
        if (data.activated_at !== undefined) updatePayload.activated_at = data.activated_at;
        
        
        if (data.activated_by !== undefined) updatePayload.activated_by = data.activated_by;
        
        
        if (data.client_info !== undefined) updatePayload.client_info = data.client_info;
        
        
        if (data.activation_token !== undefined) updatePayload.activation_token = data.activation_token;
        
        
        if (data.result !== undefined) updatePayload.result = data.result;
        
        
        if (data.failure_reason !== undefined) updatePayload.failure_reason = data.failure_reason;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.license_key !== undefined) {
            await license_activations.setLicense_key(
              
              data.license_key,
              
              { transaction }
            );
        }
        

        
        

        

        return license_activations;
    }

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

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

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


        return license_activations;
    }

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

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

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

        await license_activations.destroy({
            transaction
        });

        return license_activations;
    }

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

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

        if (!license_activations) {
            return license_activations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.license_key = await license_activations.getLicense_key({
            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.license_keys,
        as: 'license_key',
        
        where: filter.license_key ? {
          [Op.or]: [
            { id: { [Op.in]: filter.license_key.split('|').map(term => Utils.uuid(term)) } },
            {
              license_code: {
                [Op.or]: filter.license_key.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.activated_by) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'license_activations',
                        'activated_by',
                        filter.activated_by,
                    ),
                };
            }
            
            if (filter.client_info) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'license_activations',
                        'client_info',
                        filter.client_info,
                    ),
                };
            }
            
            if (filter.activation_token) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'license_activations',
                        'activation_token',
                        filter.activation_token,
                    ),
                };
            }
            
            if (filter.failure_reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'license_activations',
                        'failure_reason',
                        filter.failure_reason,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      



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

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

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

    
};

