/**
 * Auth controller
 * - Register + Login using bcrypt
 * - Issues JWT
 */

const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

const { findByUsername, createUser } = require('../models/user.model');

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

  // Check existing user
  const existing = await findByUsername(username);
  if (existing) {
    return res.status(409).json({ error: 'USER_EXISTS', message: 'Username already exists' });
  }

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

  // Return minimal information for client
  return res.status(201).json({
    id: user.id,
    username: user.username
  });
}

async function login(req, res) {
  const { username, password } = req.body;

  const user = await findByUsername(username);
  if (!user) {
    return res.status(401).json({ error: 'INVALID_CREDENTIALS', message: 'Invalid username/password' });
  }

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

  const payload = { id: user.id, username: user.username };
  const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN || '7d' });

  return res.json({ token });
}

module.exports = { register, login };

