import express from "express";
import dotenv from "dotenv";
const router = express.Router();
dotenv.config();

import { getInfo, newEntry, confirmUser } from "./frontend.data.js";

router.post("/new-entry", async (req, res) => {
  const username = req.query.username;
  const draw = req.query.draw;

  const result = await newEntry(req.body, username, draw);
  
  if (!result.success) {
    return res.status(500).json({ message: "Form Data Invalid" });
  }
  res.sendStatus(204);
});

router.get("/info", async (req, res) => {
  const info = await getInfo();

  if (!info) {
    return res.status(500).json({ message: "Server error" });
  }

  res.json(info);
});

router.get("/confirm-user", async (req, res) => {
  const username = req.query.username;

  if (!username) {
    return res.status(400).json({ message: "Username is required" });
  }
  const user = await confirmUser(username);
  if (!user) {
    return res.status(404).json({ message: "User not found" });
  }
  res.json(user);
});

export default router;
