const express = require('express');
const bcrypt = require('bcryptjs');
const { audit, one } = require('../db');
const { publicUser, tokenFor } = require('../middleware/auth');

const router = express.Router();

router.get('/public/bootstrap', (req, res) => {
  res.json({
    appName: 'MixedAssets',
    setupComplete: Boolean(one('SELECT id FROM users LIMIT 1')),
    database: 'sqlite'
  });
});

router.post('/auth/login', (req, res) => {
  const { email, password } = req.body;
  const user = one('SELECT * FROM users WHERE lower(email) = lower(?) AND status = ?', [email || '', 'active']);
  if (!user || !bcrypt.compareSync(password || '', user.password_hash)) {
    return res.status(401).json({ error: 'Invalid email or password' });
  }
  audit(user.id, 'login', 'user', user.id, null, { email: user.email });
  return res.json({ token: tokenFor(user), user: publicUser(user) });
});

module.exports = router;
