import express from "express";
import { requireAuthenticated } from "../middleware/authority.js";
import { needDatabase } from "../middleware/database.js";
import sportModel from "../schemas/sportModel.js";
import userModel from "../schemas/userModel.js";

const SportController = express.Router();

SportController.post("/", needDatabase, requireAuthenticated, async (req, res) => {
    const user = await userModel.findById(req.session.userId);
    try {
        if (user.accessLevel <= 2) {
            res.status(403).send("Insufficient privileges.");
            return;
        }
        const sport = new sportModel({
            name: req.body.name,
            maxPlayers: req.body.maxPlayers,
            minPlayers: req.body.minPlayers,
            description: req.body.description
        });
        await sport.save();
        res.status(201).send("Successfully created new sport.");
    } catch (error) {
        res.status(500).send("Internal server error.");
        // TODO: Add proper error checking here.
    }
});

SportController.get("/:sportId", needDatabase, async (req, res) => {
    try {
        res.status(200).send(await sportModel.findById(req.params.sportId));
    } catch (error) {
        res.status(500).send("Internal server error.");
        // TODO: Add proper error checking here.
    }
});

SportController.get("/", needDatabase, async (req, res) => {
    try {
        res.status(200).send(await sportModel.find());
    } catch (error) {
        res.status(500).send("Internal server error.");
        // TODO: Add proper error checking here.
    }
});

export default SportController;