var express = require("express");
var { MongoClient, ObjectId } = require("mongodb");
var cors = require("cors");
var bodyParser = require("body-parser");

var app = express();
app.use(cors());
app.use(bodyParser.json());

var CONNECTION_STRING = "mongodb://localhost:27017";
var DATABASENAME = "recipedb";
var database;

async function startServer() {
    var client = new MongoClient(CONNECTION_STRING);
    await client.connect();
    database = client.db(DATABASENAME);
    console.log("MongoDB Successfully Connected");

    app.listen(5038, () => {
        console.log("Server running on port 5038");
    });
}

startServer().catch(err => {
    console.error("Failed to connect to MongoDB:", err.message);
    process.exit(1);
});

// GET all recipes
app.get("/api/recipes/GetRecipes", async (_request, response) => {
    try {
        var result = await database.collection("recipes").find({}).toArray();
        response.send(result);
    } catch (error) {
        response.status(500).send({ message: error.message });
    }
});

// GET single recipe by id
app.get("/api/recipes/GetRecipe/:id", async (request, response) => {
    try {
        var result = await database.collection("recipes").findOne(
            { _id: new ObjectId(request.params.id) }
        );
        if (!result) return response.status(404).send({ message: "Recipe not found" });
        response.send(result);
    } catch (error) {
        response.status(500).send({ message: error.message });
    }
});

// POST create a new recipe
app.post("/api/recipes/AddRecipe", async (request, response) => {
    try {
        var recipe = {
            title: request.body.title,
            description: request.body.description,
            category: request.body.category,
            ingredients: request.body.ingredients,
            instructions: request.body.instructions,
            prepTime: request.body.prepTime,
            cookTime: request.body.cookTime,
            rating: request.body.rating,
            createdAt: new Date()
        };
        var result = await database.collection("recipes").insertOne(recipe);
        response.send(result);
    } catch (error) {
        response.status(500).send({ message: error.message });
    }
});

// PUT update a recipe by id
app.put("/api/recipes/UpdateRecipe/:id", async (request, response) => {
    try {
        var result = await database.collection("recipes").updateOne(
            { _id: new ObjectId(request.params.id) },
            {
                $set: {
                    title: request.body.title,
                    description: request.body.description,
                    category: request.body.category,
                    ingredients: request.body.ingredients,
                    instructions: request.body.instructions,
                    prepTime: request.body.prepTime,
                    cookTime: request.body.cookTime,
                    rating: request.body.rating
                }
            }
        );
        response.send(result);
    } catch (error) {
        response.status(500).send({ message: error.message });
    }
});

// DELETE a recipe by id
app.delete("/api/recipes/DeleteRecipe/:id", async (request, response) => {
    try {
        var result = await database.collection("recipes").deleteOne(
            { _id: new ObjectId(request.params.id) }
        );
        response.send(result);
    } catch (error) {
        response.status(500).send({ message: error.message });
    }
});
