const express = require("express");
const router = express.Router();
const { query } = require("../mods/dbconnection");
const config = require("../conf/config.json");
const authMiddleware = require("../middleware/authMiddleware");
const adminMiddleware = require("../middleware/adminMiddleware");


router.post("/getBeltMinMax", authMiddleware, async (req, res) => {
    try {
        const rows = await query(`
            SELECT type, level
            FROM \`boas-se\`.tb_sensor_data_min_max
            WHERE type IN ('belt_min', 'belt_max')
        `);

        const result = {
            belt_min: null,
            belt_max: null,
        };

        rows.forEach(row => {
            result[row.type] = row.level;
        });

        return res.json({
            ok: true,
            minmax: result,
        });

    } catch (err) {
        console.error("[getBeltMinMax ERROR]");
        console.error(err);

        return res.status(500).json({
            ok: false,
            msg: "오류 발생",
            error: process.env.NODE_ENV === "development"
                ? err.message
                : undefined,
        });
    }
});

router.post("/getRopeMinMax", authMiddleware, async (req, res) => {
    try {
        const rows = await query(`
            SELECT type, level
            FROM \`boas-se\`.tb_sensor_data_min_max
            WHERE type IN ('rope_min', 'rope_max')
        `);

        const result = {
            rope_min: null,
            rope_max: null,
        };

        rows.forEach(row => {
            result[row.type] = row.level;
        });

        return res.json({
            ok: true,
            minmax: result,
        });

    } catch (err) {
        console.error("[getRopeMinMax ERROR]");
        console.error(err);

        return res.status(500).json({
            ok: false,
            msg: "오류 발생",
            error: process.env.NODE_ENV === "development"
                ? err.message
                : undefined,
        });
    }
});

router.put("/updateBeltMinMax", authMiddleware, async (req, res) => {
    try {
        const { belt_min, belt_max } = req.body;

        if (belt_min === undefined || belt_max === undefined) {
            return res.status(400).json({
                ok: false,
                msg: "belt_min, belt_max가 필요합니다.",
            });
        }

        const beltMin = Number(belt_min);
        const beltMax = Number(belt_max);

        if (!Number.isFinite(beltMin) || !Number.isFinite(beltMax)) {
            return res.status(400).json({
                ok: false,
                msg: "belt_min, belt_max는 숫자여야 합니다.",
            });
        }

        if (beltMin > beltMax) {
            return res.status(400).json({
                ok: false,
                msg: "belt_min은 belt_max보다 클 수 없습니다.",
            });
        }

        await query(
            `
            UPDATE \`boas-se\`.tb_sensor_data_min_max
            SET level = CASE type
                WHEN 'belt_min' THEN ?
                WHEN 'belt_max' THEN ?
            END
            WHERE type IN ('belt_min', 'belt_max')
            `,
            [beltMin, beltMax]
        );

        return res.json({
            ok: true,
            msg: "Belt 허용치가 수정되었습니다.",
        });

    } catch (err) {
        console.error("[updateBeltMinMax ERROR]");
        console.error(err);

        return res.status(500).json({
            ok: false,
            msg: "오류 발생",
            error: process.env.NODE_ENV === "development"
                ? err.message
                : undefined,
        });
    }
});

router.put("/updateRopeMinMax", authMiddleware, async (req, res) => {
    try {
        const { rope_min, rope_max } = req.body;

        if (rope_min === undefined || rope_max === undefined) {
            return res.status(400).json({
                ok: false,
                msg: "rope_min, rope_max가 필요합니다.",
            });
        }

        const ropeMin = Number(rope_min);
        const ropeMax = Number(rope_max);

        if (!Number.isFinite(ropeMin) || !Number.isFinite(ropeMax)) {
            return res.status(400).json({
                ok: false,
                msg: "rope_min, rope_max는 숫자여야 합니다.",
            });
        }

        if (ropeMin < 0 || ropeMax < 0) {
            return res.status(400).json({
                ok: false,
                msg: "Rope 허용 오차는 음수가 될 수 없습니다.",
            });
        }

        await query(
            `
            UPDATE \`boas-se\`.tb_sensor_data_min_max
            SET level = CASE type
                WHEN 'rope_min' THEN ?
                WHEN 'rope_max' THEN ?
            END
            WHERE type IN ('rope_min', 'rope_max')
            `,
            [ropeMin, ropeMax]
        );

        return res.json({
            ok: true,
            msg: "Rope 허용치가 수정되었습니다.",
        });

    } catch (err) {
        console.error("[updateRopeMinMax ERROR]");
        console.error(err);

        return res.status(500).json({
            ok: false,
            msg: "오류 발생",
            error: process.env.NODE_ENV === "development"
                ? err.message
                : undefined,
        });
    }
});

module.exports = router;