'use strict';

const express  = require('express');
const router   = express.Router();
const fs       = require('fs');
const path     = require('path');
const bcrypt   = require('bcryptjs');
const jwt      = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
const { requireAuth, requireSuperAdmin, JWT_SECRET, JWT_EXPIRY } = require('../middleware/auth');

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

// ─── Helpers ──────────────────────────────────────────────────────────────────
function readUsers() {
  if (!fs.existsSync(USERS_PATH)) return [];
  try { return JSON.parse(fs.readFileSync(USERS_PATH, 'utf8')); } catch { return []; }
}

function writeUsers(users) {
  fs.mkdirSync(path.dirname(USERS_PATH), { recursive: true });
  fs.writeFileSync(USERS_PATH, JSON.stringify(users, null, 2));
}

function safeUser(u) {
  const { passwordHash, ...rest } = u;
  return rest;
}

// ─── Seed default superadmin if no users exist ───────────────────────────────
function seedDefaultAdmin() {
  const users = readUsers();
  if (users.length === 0) {
    const hash = bcrypt.hashSync('Admin@123', 12);
    writeUsers([{
      id:           uuidv4(),
      username:     'admin',
      displayName:  'Administrator',
      role:         'superadmin',
      passwordHash: hash,
      createdAt:    new Date().toISOString(),
      lastLogin:    null,
    }]);
    console.log('  ► Default admin created  —  admin / Admin@123  (change this!)');
  }
}
seedDefaultAdmin();

// ─── POST /api/auth/login ─────────────────────────────────────────────────────
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 = readUsers();
  const user  = users.find(u => u.username === username);
  if (!user || !bcrypt.compareSync(password, user.passwordHash))
    return res.status(401).json({ error: 'Invalid username or password' });

  // Update lastLogin
  user.lastLogin = new Date().toISOString();
  writeUsers(users);

  const token = jwt.sign(
    { id: user.id, username: user.username, role: user.role, displayName: user.displayName },
    JWT_SECRET,
    { expiresIn: JWT_EXPIRY }
  );

  res.json({ token, user: safeUser(user) });
});

// ─── GET /api/auth/me ─────────────────────────────────────────────────────────
router.get('/me', requireAuth, (req, res) => {
  const users = readUsers();
  const user  = users.find(u => u.id === req.user.id);
  if (!user) return res.status(404).json({ error: 'User not found' });
  res.json(safeUser(user));
});

// ─── GET /api/auth/users  (superadmin) ───────────────────────────────────────
router.get('/users', requireAuth, requireSuperAdmin, (_req, res) => {
  res.json(readUsers().map(safeUser));
});

// ─── POST /api/auth/users  create (superadmin) ───────────────────────────────
router.post('/users', requireAuth, requireSuperAdmin, (req, res) => {
  const { username, password, displayName, role } = req.body || {};
  if (!username || !password) return res.status(400).json({ error: 'Username and password required' });

  const validRoles = ['superadmin', 'user'];
  if (role && !validRoles.includes(role))
    return res.status(400).json({ error: 'Invalid role' });

  const users = readUsers();
  if (users.find(u => u.username === username))
    return res.status(409).json({ error: 'Username already exists' });

  const newUser = {
    id:           uuidv4(),
    username,
    displayName:  displayName || username,
    role:         role || 'user',
    passwordHash: bcrypt.hashSync(password, 12),
    createdAt:    new Date().toISOString(),
    lastLogin:    null,
  };
  users.push(newUser);
  writeUsers(users);
  res.status(201).json(safeUser(newUser));
});

// ─── PUT /api/auth/users/:id  update (superadmin or self for password) ───────
router.put('/users/:id', requireAuth, (req, res) => {
  const isSuperAdmin = req.user.role === 'superadmin';
  const isSelf       = req.user.id === req.params.id;

  if (!isSuperAdmin && !isSelf)
    return res.status(403).json({ error: 'Access denied' });

  const users = readUsers();
  const idx   = users.findIndex(u => u.id === req.params.id);
  if (idx === -1) return res.status(404).json({ error: 'User not found' });

  const { password, displayName, role } = req.body || {};

  if (password) {
    if (password.length < 8)
      return res.status(400).json({ error: 'Password must be at least 8 characters' });
    users[idx].passwordHash = bcrypt.hashSync(password, 12);
  }
  if (displayName)          users[idx].displayName = displayName;
  if (role && isSuperAdmin) users[idx].role        = role;

  writeUsers(users);
  res.json(safeUser(users[idx]));
});

// ─── DELETE /api/auth/users/:id  (superadmin, cannot delete self) ────────────
router.delete('/users/:id', requireAuth, requireSuperAdmin, (req, res) => {
  if (req.user.id === req.params.id)
    return res.status(400).json({ error: 'Cannot delete your own account' });

  const users  = readUsers();
  const before = users.length;
  const after  = users.filter(u => u.id !== req.params.id);
  if (after.length === before) return res.status(404).json({ error: 'User not found' });
  writeUsers(after);
  res.json({ ok: true });
});

module.exports = router;
