/**
 * ==================================================
 * Smart Attendance System
 * Settings Service
 * ==================================================
 */


const db = require("../../../config/db");


const {
    validateCategory
}
=
require("../validators/settings.validator");



class SettingsService {



    /**
     * Get Settings By Category
     *
     * Example:
     * general
     * attendance
     * device
     */
    async getCategory(category) {


        if(!validateCategory(category)){


            throw new Error(
                "Invalid settings category"
            );


        }



        const [rows] = await db.query(


            `
            SELECT

                setting_key,

                setting_value,

                description


            FROM settings


            WHERE category = ?


            ORDER BY id

            `,


            [

                category

            ]


        );



        const result = {};



        rows.forEach((row)=>{


            result[row.setting_key] =

                row.setting_value;


        });



        return result;


    }





    /**
     * Update Settings
     *
     * category:
     * general
     * attendance
     * device
     */
    async updateCategory(category,data){



        if(!validateCategory(category)){


            throw new Error(

                "Invalid settings category"

            );


        }



        if(!data || typeof data !== "object"){


            throw new Error(

                "Invalid settings data"

            );


        }



        const connection =

        await db.getConnection();




        try{


            await connection.beginTransaction();




            for(const key in data){



                await connection.query(


                    `
                    UPDATE settings

                    SET

                        setting_value = ?

                    WHERE

                        category = ?

                    AND

                        setting_key = ?

                    `,


                    [

                        data[key],

                        category,

                        key

                    ]


                );



            }




            await connection.commit();



            return await this.getCategory(

                category

            );



        }



        catch(error){



            await connection.rollback();


            throw error;



        }



        finally{


            connection.release();


        }


    }




}



module.exports =

new SettingsService();