const bcrypt = require("bcryptjs");
const User = require("../model/User");

const SALT_ROUNDS = Number(process.env.BCRYPT_SALT_ROUNDS) || 10;

const login = async (req, res) => {
  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 }).lean();
  if (!user) return res.status(401).json({ message: "Invalid credentials" });

  // Backward compatibility: if password in DB isn't a bcrypt hash, keep old behavior.
  const isMatch =
    typeof user.password === "string" && user.password.startsWith("$")
      ? await bcrypt.compare(password, user.password)
      : user.password === password;

  if (!isMatch) return res.status(401).json({ message: "Invalid credentials" });

  req.session.user = {
    id: user._id,
    username: user.username,
    fullName: user.fullName,
  };

  return res.json({ message: "Login successful", user: req.session.user });
};

const register = async (req, res) => {
  const { username, password, fullName } = req.body;

  if (!username || !password || !fullName) {
    return res.status(400).json({ message: "username, password and fullName are required" });
  }

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

  const hashedPassword = await bcrypt.hash(password, SALT_ROUNDS);

  const user = await User.create({ username, password: hashedPassword, fullName });

  return res.status(201).json({ message: "Registration successful", user: { id: user._id, username: user.username, fullName: user.fullName } });
};

const logout = (req, res) => {
  req.session.destroy(() => {
    res.json({ message: "Logged out" });
  });
};

const session = (req, res) => {
  if (!req.session?.user) {
    return res.status(401).json({ message: "No active session" });
  }
  return res.json({ user: req.session.user });
};

module.exports = { register, login, logout, session };
