const express = require("express");
const app = express();
const cors = require("cors");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
require("dotenv").config();
app.use(cors());

const MONGO_DB_URI =
  process.env.MONGO_DB_URI ||
  "mongodb://usenarme:password@mongodb-service:27017/devops?readPreference=primary&appname=MongoDB%20Compass&directConnection=true&ssl=false";

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());

/**
 * @description database connection
 */
mongoose
  .connect(MONGO_DB_URI, {
    useUnifiedTopology: true,
    useNewUrlParser: true,
    keepAlive: true,
  })
  .then(() => console.log("MongoDB connected [%s]", MONGO_DB_URI))
  .catch((err) => console.log(`DB connection error : ${err.reason}`));

/**
 * @description Quotation Model
 */
const Quotation = mongoose.model("quotations", {
  name: String,
  quotation: String,
});

/**
 * @description get api for base route
 */
app.get("/", (req, res, next) => {
  res.json({ message: "server is working fine..." });
});

/**
 * @description get quotation list
 */
app.get("/quotations", async (req, res, next) => {
  const quotations = await Quotation.find({});
  res.json({ message: "Quotation List", data: { quotations } });
});

/**
 * @description create new quotation
 */
app.post("/quotation", async (req, res, next) => {
  const quotation = new Quotation();
  console.log("req.body", req.body);
  quotation.name = req.body.name;
  quotation.quotation = req.body.quotation;
  await quotation.save();
  res.json({ message: "Quotation Created Successfully", data: { quotation } });
});

/**
 * @description start server
 */
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
  console.log(`Server is running on PORT: ${PORT}`);
});
