// variables 
const PORT = process.env.PORT || 3000;


const express = require("express");
const { logger } = require("./logger");
const { setup, initOraclePool, productUtils, createError } = require("./utils");
const poolSettings = require("./settings");


const app = express();

// json body parser
app.use(express.json())

// setup oracle client libraries for thick mode.
setup(poolSettings);

const router = express.Router();

router.post("/", async (req, res, next) => {
    try {
        const id = await productUtils.create(req.body);
        res.status(201).json(id);
    } catch (error) {
        next(error);
    }
});

router.get("/:id", async (req, res, next) => {
    try {
        const record = await productUtils.findById(req.params.id);
        res.json(record);
    } catch (error) {
        next(error);
    }
});

router.patch("/:id", async (req, res, next) => {
    const { id } = req.params;
    try {
        if (!id) {
            throw createError(new Error("Product Id is required"), 400)
        }
        res.json(await productUtils.patchById(id, req.body));
    } catch (error) {
        next(error);
    }
});

router.delete("/:id", async (req, res, next) => {
    const { id } = req.params;
    try {
        if (!id) {
            throw createError(new Error("Product ID is required"), 400)
        }
        await productUtils.deleteById(id);
        res.status(200).json({ message: "Product deleted successfully" });
    } catch (error) {
        next(error);
    }
});

app.use("/api/Products", reqLogger, router);

let cnt = 1;

function reqLogger(req, res, next) {
    logger.info("Request cnt: " + cnt++);
    next();
}

app.use((err, req, res, next) => {
    res.status(err.status || 500).json({ error: err.message });
    next(err);
})

initOraclePool(poolSettings)
    .then(() => {
        app.listen(PORT, () => {
            logger.info(`server started on port: ${PORT}`);
        });
    })
    .catch((err) => {
        console.error(err);
    });

