import express, { Request } from "express";
import { getLogin } from "../auth";
import { parseToken } from "../utils";
import { getUserVotes, updateFeatureVote, getVotingStats } from "../voting";
import { GetVotesData, UpdateVoteData } from "../../../types";

const router = express.Router();

router.get("/getVotes", async (req: Request<{}, any, GetVotesData["body"]>, res) => {
    const login = getLogin(parseToken(req));
    const data = await getUserVotes(login);
    res.status(200).json(data);
});

router.post("/updateVote", async (req: Request<{}, any, UpdateVoteData["body"]>, res, next) => {
    const login = getLogin(parseToken(req));
    if (req.body?.option == null || req.body?.active == null) {
        res.status(400).json({ error: "Chybné parametry volání" });
    }
    try {
        const data = await updateFeatureVote(login, req.body.option, req.body.active);
        res.status(200).json(data);
    } catch (e: any) { next(e) }
});

router.get("/stats", async (req, res, next) => {
    try {
        const data = await getVotingStats();
        res.status(200).json(data);
    } catch (e: any) { next(e) }
});

export default router;