const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { query } = require('../db');
const config = require('../config');

const router = express.Router();

router.post('/login', async (req, res) => {
  const { email, password } = req.body;
  if (!email || !password) return res.status(400).json({ error: 'Missing email/password' });

  const rows = await query('SELECT id, company_id, name, role, password_hash FROM employees WHERE email = ? AND is_active = 1', [email]);
  const user = rows[0];
  if (!user) return res.status(401).json({ error: 'Invalid credentials' });

  const match = await bcrypt.compare(password, user.password_hash);
  if (!match) return res.status(401).json({ error: 'Invalid credentials' });

  const token = jwt.sign({ id: user.id, role: user.role, companyId: user.company_id }, config.jwt.secret, { expiresIn: config.jwt.expiresIn });
  res.json({ token, user: { id: user.id, name: user.name, role: user.role, companyId: user.company_id } });
});

module.exports = router;
