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

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

        const api_providers = await db.api_providers.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        base_url: data.base_url
        ||
        null
            ,
            
        provider_type: data.provider_type
        ||
        null
            ,
            
        enabled: data.enabled
        ||
        false
        
            ,
            
        last_health_check_at: data.last_health_check_at
        ||
        null
            ,
            
        health_status: data.health_status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return api_providers;
    }
    

    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_providersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                base_url: item.base_url
            ||
            null
            ,
            
                provider_type: item.provider_type
            ||
            null
            ,
            
                enabled: item.enabled
            ||
            false
        
            ,
            
                last_health_check_at: item.last_health_check_at
            ||
            null
            ,
            
                health_status: item.health_status
            ||
            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_providers = await db.api_providers.bulkCreate(api_providersData, { transaction });

        // For each item created, replace relation files
        

        return api_providers;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.base_url !== undefined) updatePayload.base_url = data.base_url;
        
        
        if (data.provider_type !== undefined) updatePayload.provider_type = data.provider_type;
        
        
        if (data.enabled !== undefined) updatePayload.enabled = data.enabled;
        
        
        if (data.last_health_check_at !== undefined) updatePayload.last_health_check_at = data.last_health_check_at;
        
        
        if (data.health_status !== undefined) updatePayload.health_status = data.health_status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return api_providers;
    }

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

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

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


        return api_providers;
    }

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

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

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

        await api_providers.destroy({
            transaction
        });

        return api_providers;
    }

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

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

        if (!api_providers) {
            return api_providers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

        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 = [



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'api_providers',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.base_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'api_providers',
                        'base_url',
                        filter.base_url,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'api_providers',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.provider_type) {
                where = {
                    ...where,
                provider_type: filter.provider_type,
            };
            }
            
            if (filter.enabled) {
                where = {
                    ...where,
                enabled: filter.enabled,
            };
            }
            
            if (filter.health_status) {
                where = {
                    ...where,
                health_status: filter.health_status,
            };
            }
            




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

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

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

    
};

