const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/User');

function validateRegisterBody(body) {
  const { username, password } = body || {};
  if (!username || typeof username !== 'string' || username.trim().length < 3) {
    return 'username is required and must be at least 3 characters';
  }
  if (!password || typeof password !== 'string' || password.length < 6) {
    return 'password is required and must be at least 6 characters';
  }
  return null;
}

async function register(req, res, next) {
  try {
    const errMsg = validateRegisterBody(req.body);
    if (errMsg) return res.status(400).json({ message: errMsg });

    const existing = await User.findOne({ username: req.body.username.trim() });
    if (existing) return res.status(400).json({ message: 'Username already exists' });

    const hashedPassword = await bcrypt.hash(req.body.password, 10);

    const user = await User.create({ username: req.body.username.trim(), password: hashedPassword });
    return res.status(201).json({ id: user._id, username: user.username });
  } catch (err) {
    return next(err);
  }
}

async function login(req, res, next) {
  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 username or password' });

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

    const token = jwt.sign({ userId: user._id, username: user.username }, process.env.JWT_SECRET, {
      expiresIn: '7d'
    });

    res.cookie('token', token, {
      httpOnly: true,
      sameSite: 'lax'
      // secure: true // enable if you use HTTPS
    });

    return res.status(200).json({ message: 'Login successful', token });
  } catch (err) {
    return next(err);
  }
}

async function logout(req, res, next) {
  try {
    res.clearCookie('token');
    return res.status(200).json({ message: 'Logout successful' });
  } catch (err) {
    return next(err);
  }
}

async function profile(req, res, next) {
  try {
    // authMiddleware sets req.user
    return res.status(200).json({ user: req.user });
  } catch (err) {
    return next(err);
  }
}

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

