const usersDb = require('../../shared/usersDb');
const makeLinks = require('../../shared/hateoas');

exports.login = (req, res) => {
  const { username, password, email } = req.body;
  const user = usersDb.findUser(username, email, password);
  if (user) {
    res.json({
      data: {
        user: {
          id: user.id,
          username: user.username,
          email: user.email,
          firstName: user.firstName,
          lastName: user.lastName
        },
        token: 'token-' + user.id,
        message: 'Login successful'
      },
      _links: makeLinks('/api/auth', {
        self: '/login',
        profile: '/profile/',
        logout: '/logout'
      }),
      _meta: {}
    });
  } else {
    res.status(401).json({ error: 'Invalid credentials' });
  }
};

exports.register = (req, res) => {
  const { username, password, email, firstName, lastName } = req.body;
  if (usersDb.exists(username, email)) {
    return res.status(409).json({ error: 'User already exists' });
  }
  const newUser = usersDb.addUser({ username, password, email, firstName, lastName });
  res.json({
    data: {
      user: {
        id: newUser.id,
        username,
        email,
        firstName,
        lastName
      },
      token: 'token-' + newUser.id,
      message: 'Register successful'
    },
    _links: makeLinks('/api/auth', {
      self: '/register',
      login: '/login',
      profile: '/profile/'
    }),
    _meta: {}
  });
};

exports.profile = (req, res) => {
  const auth = req.headers.authorization;
  if (!auth || !auth.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'No token provided' });
  }
  const token = auth.replace('Bearer ', '');
  const id = parseInt(token.replace('token-', ''));
  const user = usersDb.findById(id);
  if (!user) {
    return res.status(401).json({ error: 'Invalid token' });
  }
  res.json({
    data: {
      id: user.id,
      username: user.username,
      email: user.email,
      firstName: user.firstName,
      lastName: user.lastName
    },
    _links: makeLinks('/api/auth', {
      self: '/profile/',
      logout: '/logout'
    }),
    _meta: {}
  });
};

exports.logout = (req, res) => {
  res.json({
    message: 'Logout successful',
    _links: makeLinks('/api/auth', {
      self: '/logout',
      login: '/login'
    }),
    _meta: {}
  });
}; 