const express = require('express');
const bcrypt = require('bcryptjs');
const { all, audit, now, one, run } = require('../db');
const { requireRole } = require('../middleware/auth');
const { isValidRole, roleCapabilities, rolePermissions, roles } = require('../services/accessControl');

const router = express.Router();

const userSelect = `
  SELECT u.id, u.team_id, t.name AS team_name, u.name, u.email, u.role, u.status, u.created_at, u.updated_at
  FROM users u
  LEFT JOIN teams t ON t.id = u.team_id
`;

function publicAdminUser(id) {
  return one(`${userSelect} WHERE u.id = ?`, [id]);
}

function validateRole(role) {
  if (!isValidRole(role)) throw Object.assign(new Error('Invalid role'), { status: 400 });
}

router.get('/settings', requireRole('admin'), (req, res) => {
  const rows = all('SELECT * FROM app_settings ORDER BY key');
  res.json({ settings: Object.fromEntries(rows.map((row) => [row.key, row.value])) });
});

router.put('/settings', requireRole('admin'), (req, res) => {
  for (const [key, value] of Object.entries(req.body.settings || req.body)) {
    run('INSERT INTO app_settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at', [
      key,
      String(value),
      now()
    ]);
  }
  audit(req.user.id, 'update', 'settings', 'app', null, req.body);
  res.json({ settings: Object.fromEntries(all('SELECT * FROM app_settings ORDER BY key').map((row) => [row.key, row.value])) });
});

router.get('/users', requireRole('admin'), (req, res) => {
  res.json({ users: all(`${userSelect} ORDER BY u.name`) });
});

router.post('/users', requireRole('admin'), (req, res) => {
  validateRole(req.body.role || 'viewer');
  if (req.body.status && !['active', 'inactive'].includes(req.body.status)) return res.status(400).json({ error: 'Invalid status' });
  const created = now();
  const result = run(
    'INSERT INTO users (team_id, name, email, password_hash, role, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
    [
      req.body.team_id || one('SELECT id FROM teams ORDER BY id LIMIT 1')?.id,
      req.body.name,
      req.body.email,
      bcrypt.hashSync(req.body.password || 'ChangeMe123!', 12),
      req.body.role || 'viewer',
      req.body.status || 'active',
      created,
      created
    ]
  );
  audit(req.user.id, 'create', 'user', result.lastInsertRowid, null, { ...req.body, password: '[redacted]' });
  res.status(201).json({ user: publicAdminUser(result.lastInsertRowid) });
});

router.put('/users/:id', requireRole('admin'), (req, res) => {
  const before = publicAdminUser(req.params.id);
  if (!before) return res.status(404).json({ error: 'User not found' });
  const nextRole = req.body.role || before.role;
  validateRole(nextRole);

  const nextStatus = req.body.status || before.status;
  if (!['active', 'inactive'].includes(nextStatus)) return res.status(400).json({ error: 'Invalid status' });

  const activeAdmins = one("SELECT COUNT(*) AS count FROM users WHERE role = 'admin' AND status = 'active'").count;
  if (before.role === 'admin' && before.status === 'active' && activeAdmins <= 1 && (nextRole !== 'admin' || nextStatus !== 'active')) {
    return res.status(400).json({ error: 'At least one active admin is required' });
  }

  const updated = now();
  run(
    `UPDATE users SET
      team_id = ?,
      name = ?,
      email = ?,
      role = ?,
      status = ?,
      updated_at = ?
     WHERE id = ?`,
    [
      req.body.team_id ?? before.team_id,
      req.body.name || before.name,
      req.body.email || before.email,
      nextRole,
      nextStatus,
      updated,
      req.params.id
    ]
  );

  if (req.body.password) {
    run('UPDATE users SET password_hash = ?, updated_at = ? WHERE id = ?', [
      bcrypt.hashSync(req.body.password, 12),
      updated,
      req.params.id
    ]);
  }

  const user = publicAdminUser(req.params.id);
  audit(req.user.id, 'update', 'user', req.params.id, before, { ...user, password: req.body.password ? '[changed]' : undefined });
  return res.json({ user });
});

router.get('/teams', requireRole('admin'), (req, res) => {
  res.json({ teams: all('SELECT * FROM teams ORDER BY name') });
});

router.post('/teams', requireRole('admin'), (req, res) => {
  const result = run('INSERT INTO teams (name, description, created_at) VALUES (?, ?, ?)', [
    req.body.name,
    req.body.description || null,
    now()
  ]);
  audit(req.user.id, 'create', 'team', result.lastInsertRowid, null, req.body);
  res.status(201).json({ team: one('SELECT * FROM teams WHERE id = ?', [result.lastInsertRowid]) });
});

router.get('/access-control', requireRole('admin'), (req, res) => {
  res.json({ roles, rolePermissions, roleCapabilities });
});

module.exports = router;
