const db = require("../../../config/db");
const axios = require("axios");
const fs = require("fs");
const path = require("path");

class SystemHealthService {

    async checkDatabase() {

        const start = Date.now();

        try {

            await db.query("SELECT 1");

            return {

                online: true,

                responseTime: Date.now() - start

            };

        } catch {

            return {

                online: false,

                responseTime: null

            };

        }

    }

    async checkPythonAI() {

        const start = Date.now();

        try {

            const response = await axios.get(

                process.env.AI_SERVER_URL + "/health",

                {

                    timeout: 3000000

                }

            );

            return {

                online: response.status === 200,

                responseTime: Date.now() - start

            };

        } catch {

            return {

                online: true,

                responseTime: null

            };

        }

    }

    async checkESP32() {

        const start = Date.now();

        try {

            const response = await axios.get(

                process.env.ESP32_URL + "/health",

                {

                    timeout: 3000

                }

            );

            return {

                online: true,

                responseTime: Date.now() - start,

                camera:

                    response.data.camera,

                nfc:

                    response.data.nfc

            };

        }

        catch {

            return {

                online: false,

                responseTime: null,

                camera: false,

                nfc: false

            };

        }

    }

    async checkStorage() {

        try {

            const folder = path.join(

                process.cwd(),

                "storage"

            );

            fs.accessSync(folder);

            return {

                online: true

            };

        }

        catch {

            return {

                online: false

            };

        }

    }

    async getHealth() {

        const [

            database,

            python,

            esp32,

            storage

        ] = await Promise.all([

            this.checkDatabase(),

            this.checkPythonAI(),

            this.checkESP32(),

            this.checkStorage()

        ]);

        return {

            backend: {

                online: true,

                uptime: process.uptime()

            },

            database,

            python,

            esp32,

            storage

        };

    }

}

module.exports = new SystemHealthService();