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

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

        const license_keys = await db.license_keys.create(
            {
                id: data.id || undefined,
        
        license_code: data.license_code
        ||
        null
            ,
            
        license_type: data.license_type
        ||
        null
            ,
            
        issued_at: data.issued_at
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        hardware_fingerprint: data.hardware_fingerprint
        ||
        null
            ,
            
        server_fingerprint: data.server_fingerprint
        ||
        null
            ,
            
        db_fingerprint: data.db_fingerprint
        ||
        null
            ,
            
        allowed_clients: data.allowed_clients
        ||
        null
            ,
            
        allow_updates: data.allow_updates
        ||
        false
        
            ,
            
        last_error_message: data.last_error_message
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await license_keys.setLicense_customer( data.license_customer || null, {
            transaction,
        });
        
        await license_keys.setProduct( data.product || null, {
            transaction,
        });
        

        

        

        return license_keys;
    }
    

    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_keysData = data.map((item, index) => ({
                id: item.id || undefined,
                
                license_code: item.license_code
            ||
            null
            ,
            
                license_type: item.license_type
            ||
            null
            ,
            
                issued_at: item.issued_at
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                hardware_fingerprint: item.hardware_fingerprint
            ||
            null
            ,
            
                server_fingerprint: item.server_fingerprint
            ||
            null
            ,
            
                db_fingerprint: item.db_fingerprint
            ||
            null
            ,
            
                allowed_clients: item.allowed_clients
            ||
            null
            ,
            
                allow_updates: item.allow_updates
            ||
            false
        
            ,
            
                last_error_message: item.last_error_message
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return license_keys;
    }

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

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


        

        const updatePayload = {};
        
        if (data.license_code !== undefined) updatePayload.license_code = data.license_code;
        
        
        if (data.license_type !== undefined) updatePayload.license_type = data.license_type;
        
        
        if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.hardware_fingerprint !== undefined) updatePayload.hardware_fingerprint = data.hardware_fingerprint;
        
        
        if (data.server_fingerprint !== undefined) updatePayload.server_fingerprint = data.server_fingerprint;
        
        
        if (data.db_fingerprint !== undefined) updatePayload.db_fingerprint = data.db_fingerprint;
        
        
        if (data.allowed_clients !== undefined) updatePayload.allowed_clients = data.allowed_clients;
        
        
        if (data.allow_updates !== undefined) updatePayload.allow_updates = data.allow_updates;
        
        
        if (data.last_error_message !== undefined) updatePayload.last_error_message = data.last_error_message;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.license_customer !== undefined) {
            await license_keys.setLicense_customer(
              
              data.license_customer,
              
              { transaction }
            );
        }
        
        if (data.product !== undefined) {
            await license_keys.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        

        
        

        

        return license_keys;
    }

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

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

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


        return license_keys;
    }

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

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

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

        await license_keys.destroy({
            transaction
        });

        return license_keys;
    }

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

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

        if (!license_keys) {
            return license_keys;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.license_activations_license_key = await license_keys.getLicense_activations_license_key({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.license_customer = await license_keys.getLicense_customer({
            transaction
        });
        
        
        output.product = await license_keys.getProduct({
            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_customers,
        as: 'license_customer',
        
        where: filter.license_customer ? {
          [Op.or]: [
            { id: { [Op.in]: filter.license_customer.split('|').map(term => Utils.uuid(term)) } },
            {
              customer_name: {
                [Op.or]: filter.license_customer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.license_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'license_keys',
                        'license_code',
                        filter.license_code,
                    ),
                };
            }
            
            if (filter.hardware_fingerprint) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'license_keys',
                        'hardware_fingerprint',
                        filter.hardware_fingerprint,
                    ),
                };
            }
            
            if (filter.server_fingerprint) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'license_keys',
                        'server_fingerprint',
                        filter.server_fingerprint,
                    ),
                };
            }
            
            if (filter.db_fingerprint) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'license_keys',
                        'db_fingerprint',
                        filter.db_fingerprint,
                    ),
                };
            }
            
            if (filter.last_error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'license_keys',
                        'last_error_message',
                        filter.last_error_message,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.license_type) {
                where = {
                    ...where,
                license_type: filter.license_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.allow_updates) {
                where = {
                    ...where,
                allow_updates: filter.allow_updates,
            };
            }
            


      

      



            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_keys.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_keys',
                        'license_code',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

