const express = require('express');
const bcrypt  = require('bcryptjs');
const jwt     = require('jsonwebtoken');
const fs      = require('fs');
const path    = require('path');
const router  = express.Router();
const { writeAudit } = require('./audit');

const DB_PATH = path.join(__dirname, '../data/users.json');

function loadUsers() {
  if (!fs.existsSync(DB_PATH)) return null;
  return JSON.parse(fs.readFileSync(DB_PATH));
}

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

  const users = loadUsers();

  // ── Primary path: users.json exists ──────────────────────
  if (users) {
    const user = users.find(u => u.username === username);
    if (!user || !bcrypt.compareSync(password, user.password)) {
      writeAudit({ username: username || 'unknown', ip: req.ip }, 'auth.login.fail', `Failed login attempt for "${username}"`);
      return res.status(401).json({ error: 'Invalid credentials' });
    }

    const token = jwt.sign(
      { username: user.username, role: user.role, id: user.id },
      process.env.JWT_SECRET,
      { expiresIn: '8h' }
    );
    writeAudit({ username: user.username, ip: req.ip }, 'auth.login', `User "${user.username}" logged in`);
    return res.json({ token, role: user.role, username: user.username, permissions: user.permissions });
  }

  // ── Fallback: users.json not yet created ──────────────────
  const envUser = process.env.ADMIN_USER || 'admin';
  const envHash = process.env.ADMIN_PASS_HASH;

  if (username !== envUser || !envHash || !bcrypt.compareSync(password, envHash)) {
    writeAudit({ username: username || 'unknown', ip: req.ip }, 'auth.login.fail', `Failed login attempt for "${username}"`);
    return res.status(401).json({ error: 'Invalid credentials' });
  }

  const token = jwt.sign(
    { username, role: 'admin' },
    process.env.JWT_SECRET,
    { expiresIn: '8h' }
  );
  writeAudit({ username, ip: req.ip }, 'auth.login', `User "${username}" logged in (env fallback)`);
  return res.json({ token, role: 'admin', username });
});

module.exports = router;