const express = require("express");
const router = express.Router();
const config = require("../conf/config.json");

const { query } = require("../mods/dbconnection");
const workerOrAuthMiddleware = require("../middleware/workerOrAuthMiddleware");

const TABLE_SETTING_COLUMN_MAP = {
    workHistoryTable: "work_history_setting",
    completeWorkHistoryTable: "complete_work_history_setting",
    facilityDataHistoryTable: "facility_data_history_setting",
    workOrderTable: "work_order_setting",
    equipWorkStatusTable: "equip_work_status_setting",
    performanceTable: "performance_table_setting",
    facilityFaultHistoryTable: "facility_fault_table_setting",
};

router.post("/getTableSetting", workerOrAuthMiddleware, async (req, res) => {
    const userId = req.body.userId;
    const tableId = req.body.tableId;

    const columnName = TABLE_SETTING_COLUMN_MAP[tableId];

    if (!columnName) {
        return res.status(400).json({
            ok: false,
            msg: "잘못된 테이블 ID입니다.",
        });
    }

    const rows = await query(
        `SELECT ${columnName} AS setting
         FROM \`${config.dbName.boas_se}\`.tb_user_table_setting
         WHERE user_id = ?`,
        [userId]
    );

    return res.json({
        ok: true,
        setting: rows[0]?.setting ?? '',
    });
});

router.put("/saveTableSetting", workerOrAuthMiddleware, async (req, res) => {
    const userId = req.body.userId;
    const tableId = req.body.tableId;
    const setting = req.body.setting;

    const columnName = TABLE_SETTING_COLUMN_MAP[tableId];

    if (!columnName) {
        return res.status(400).json({
            ok: false,
            msg: "잘못된 테이블 ID입니다.",
        });
    }

    if (typeof setting !== "string") {
        return res.status(400).json({
            ok: false,
            msg: "setting 값이 올바르지 않습니다.",
        });
    }

    await query(
        `INSERT INTO \`${config.dbName.boas_se}\`.tb_user_table_setting (user_id, ${columnName})
         VALUES (?, ?)
         ON DUPLICATE KEY UPDATE ${columnName} = VALUES(${columnName})`,
        [userId, setting]
    );

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

module.exports = router;