import { Router } from "express";
import bcrypt from "bcryptjs";
import User from "../models/User.js";

const router = Router();

router.post("/register", async (req, res) => {
  try {
    const { username, password } = req.body;
    if (!username || !password) {
      return res.status(400).json({ message: "Username and password are required." });
    }

    const normalized = username.trim();
    const exists = await User.findOne({ username: normalized });
    if (exists) {
      return res.status(409).json({ message: "Username already exists." });
    }

    const hashed = await bcrypt.hash(password, 10);
    const user = await User.create({ username: normalized, password: hashed });

    req.session.userId = user._id.toString();
    req.session.username = normalized;

    return res.status(201).json({ message: "Account created.", username: normalized });
  } catch (err) {
    return res.status(500).json({ message: err.message });
  }
});

router.post("/login", async (req, res) => {
  try {
    const { username, password } = req.body;
    if (!username || !password) {
      return res.status(400).json({ message: "Username and password are required." });
    }

    const user = await User.findOne({ username: username.trim() });
    if (!user) {
      return res.status(401).json({ message: "Invalid credentials." });
    }

    const ok = await bcrypt.compare(password, user.password);
    if (!ok) {
      return res.status(401).json({ message: "Invalid credentials." });
    }

    req.session.userId = user._id.toString();
    req.session.username = user.username;

    return res.json({ message: "Login successful.", username: user.username });
  } catch (err) {
    return res.status(500).json({ message: err.message });
  }
});

router.post("/logout", (req, res) => {
  req.session.destroy(() => {
    res.clearCookie("cims.sid");
    res.json({ message: "Logout successful." });
  });
});

router.get("/me", (req, res) => {
  if (!req.session.userId) {
    return res.json({ authenticated: false });
  }
  return res.json({ authenticated: true, userId: req.session.userId, username: req.session.username });
});

export default router;
