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

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

        const api_clients = await db.api_clients.create(
            {
                id: data.id || undefined,
        
        client_name: data.client_name
        ||
        null
            ,
            
        client_type: data.client_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        contact_email: data.contact_email
        ||
        null
            ,
            
        contact_phone: data.contact_phone
        ||
        null
            ,
            
        api_key_label: data.api_key_label
        ||
        null
            ,
            
        issued_at: data.issued_at
        ||
        null
            ,
            
        last_used_at: data.last_used_at
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await api_clients.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return api_clients;
    }
    

    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 api_clientsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                client_name: item.client_name
            ||
            null
            ,
            
                client_type: item.client_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                contact_email: item.contact_email
            ||
            null
            ,
            
                contact_phone: item.contact_phone
            ||
            null
            ,
            
                api_key_label: item.api_key_label
            ||
            null
            ,
            
                issued_at: item.issued_at
            ||
            null
            ,
            
                last_used_at: item.last_used_at
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return api_clients;
    }

    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 api_clients = await db.api_clients.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.client_name !== undefined) updatePayload.client_name = data.client_name;
        
        
        if (data.client_type !== undefined) updatePayload.client_type = data.client_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.contact_email !== undefined) updatePayload.contact_email = data.contact_email;
        
        
        if (data.contact_phone !== undefined) updatePayload.contact_phone = data.contact_phone;
        
        
        if (data.api_key_label !== undefined) updatePayload.api_key_label = data.api_key_label;
        
        
        if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
        
        
        if (data.last_used_at !== undefined) updatePayload.last_used_at = data.last_used_at;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organizations !== undefined) {
            await api_clients.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return api_clients;
    }

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

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

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


        return api_clients;
    }

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

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

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

        await api_clients.destroy({
            transaction
        });

        return api_clients;
    }

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

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

        if (!api_clients) {
            return api_clients;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organizations = await api_clients.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.client_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'api_clients',
                        'client_name',
                        filter.client_name,
                    ),
                };
            }
            
            if (filter.contact_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'api_clients',
                        'contact_email',
                        filter.contact_email,
                    ),
                };
            }
            
            if (filter.contact_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'api_clients',
                        'contact_phone',
                        filter.contact_phone,
                    ),
                };
            }
            
            if (filter.api_key_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'api_clients',
                        'api_key_label',
                        filter.api_key_label,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'api_clients',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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


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

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

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

    
};

