import crypto from 'crypto';
import { Router } from 'express';
import { v4 as uuidv4 } from 'uuid';
import { getUserByUsername, registerUser } from '../cqrs';

const router = Router();

function hashPassword(pw: string): string {
  return crypto.createHash('sha256').update(pw)
    .digest('hex');
}

router.post('/register', async (req, res) => {
  const { username, password, displayName } = req.body;

  if (!username || !password)
    return res.status(400).json({ error: 'Missing username/password' });

  const existing = await getUserByUsername(username);

  if (existing)
    return res.status(409).json({ error: 'Username taken' });

  const user = {
    id: uuidv4(),
    username,
    passwordHash: hashPassword(password),
    displayName: displayName || username,
    createdAt: Date.now()
  };

  await registerUser(user);
  res.status(201).json({ id: user.id, username: user.username, displayName: user.displayName });
});

router.post('/login', async (req, res) => {
  const { username, password } = req.body;
  const user = await getUserByUsername(username);

  if (!user || user.passwordHash !== hashPassword(password))
    return res.status(401).json({ error: 'Invalid credentials' });

  res.json({ id: user.id, username: user.username, displayName: user.displayName });
});

export default router;
