const dbSAPPS = require('../../helpers/db');
require('dotenv').config();

module.exports = {
    create,
    getAll
};

async function create(params) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        await dbSAPPS.ApiKey.upsert(params, { transaction });
        await transaction.commit();
        return {
            success: true,
            message: 'Api key & secret has been set!'
        };

    } catch (error) {
        await transaction.rollback();
        const errorMessage = error.message || 'An error occurred during set api key & secret processing.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function getAll() {
    try {
        const apikeys = await dbSAPPS.ApiKey.findAll({
            order: [['updatedAt', 'DESC']],
        });

        return {
            apikeys,
            success: true,
            message: 'Api keys has been loaded!'
        };
    } catch (error) {
        const errorMessage = error.message || 'Failed to load api keys!';
        return {
            success: false,
            message: errorMessage
        };
    }
}
