import express from "express";
import { requireAuthenticated } from "../middleware/authority.js";
import { needDatabase } from "../middleware/database.js";
import rentalModel from "../schemas/rentalModel.js";
import userModel from "../schemas/userModel.js";
const rentalController = express.Router();


rentalController.post("/", needDatabase, requireAuthenticated, async (req, res) => {
    try {
        const user = req.user;
        req.body.createDate = undefined;
        req.body.creator = user._id;
        const rental = new rentalModel(req.body);
        await rental.save();
        res.status(201).send({ createdRental: rental });
    } catch (error) {
        console.error(error);
        res.status(500).send("Internal server error.");
    }
});

rentalController.get("/:id", needDatabase, async (req, res) => {
    try {
        const rental = await rentalModel.findById(req.params.id).populate("creator");
        res.status(200).send({ rental: rental });
    } catch (error) {
        console.error(error);
        res.status(500).send("Internal server error");
    }
});

rentalController.get("/recent/:limit?", needDatabase, async (req, res) => {
    try {
        let user = null;
        if (req.session.userId) {
            user = await userModel.findById(req.session.userId);
        }
        let limit = parseInt(req.params.limit);
        if (!req.params.limit) limit = 10;
        if (isNaN(limit)) {
            console.log(typeof (limit));
            res.status(400).send("Limit parameter is not a number.");
            return;
        }
        if (isNaN(limit)) {
            res.status(400).send("Limit parameter not a number.");
            return;
        }
        if (limit > 50) {
            res.status(400).send("Limit greater than maximum limit of 50.");
            return;
        }
        let recent = null;
        if (user) {
            await user.populate("createdRentals");
            recent = user.createdRentals.slice(-limit);
        } else {
            recent = await rentalModel.find().limit(limit).sort({ createDate: -1 });
        }
        await recent.populate("members.$");
        res.status(200).send({ recent: recent });
    } catch (error) {
        console.error(error);
        res.status(500).send("Internal server error.");
    }
});

rentalController.patch("/:id", needDatabase, requireAuthenticated, async (req, res) => {
    try {
        const rental = await rentalModel.findById(req.params.id);
        if (!rental) {
            res.status(400).send("Invalid rental ID provided.");
            return;
        }
        if (req.body._id) {
            res.status(400).send("Cannot change ID of rental.");
            return;
        }
        if (req.body.creator) {
            res.status(400).send("Cannot change creator of rental.");
            return;
        }
        if (req.user._id !== rental.creator && req.user.accessLevel < 3) {
            res.status(401).send("Not authorized.");
            return;
        }
        await rental.updateOne(req.body);
        res.status(200).send({ updated: rental });
    } catch (error) {
        console.error(error);
        res.status(500).send("Internal server error.");
    }
});

rentalController.delete("/:id", needDatabase, requireAuthenticated, async (req, res) => {
    try {
        const rental = await rentalModel.findById(req.params.id);
        if (!rental) {
            res.status(400).send("Invalid match ID provided.");
            return;
        }

        if (req.user._id !== rental.creator && req.user.accessLevel < 3) {
            res.status(401).send("Not authorized.");
            return;
        }
        await rental.deleteOne();
        res.status(200).send("Deleted.");
    } catch (error) {
        console.error(error);
        res.status(500).send("Internal server error");
    }
});

export default rentalController;