const express = require('express');
const bcrypt = require('bcryptjs');
const { all, audit, now, one, run } = require('../db');
const { requireCapability } = require('../middleware/auth');
const { CAPABILITIES } = require('../services/accessControl');
const { createRole, deleteRole, listRoles, roleExists, updateRole } = require('../services/roles');
const passwordPolicy = require('../services/passwordPolicy');
const auditTrail = require('../services/auditTrail');
const appLogs = require('../services/appLogs');

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.last_login_at, u.locked_until, u.must_change_password, u.password_changed_at,
         u.created_at, u.updated_at
  FROM users u
  LEFT JOIN teams t ON t.id = u.team_id
`;

const companies = require('../services/companies');

function publicAdminUser(id) {
  const user = one(`${userSelect} WHERE u.id = ?`, [id]);
  if (user) user.company_ids = companies.assignedCompanyIds(user.id);
  return user;
}

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

router.get('/settings', requireCapability('admin.settings'), (req, res) => {
  const rows = all('SELECT * FROM app_settings ORDER BY key');
  const settings = Object.fromEntries(rows.map((row) => [row.key, row.value]));
  delete settings.smtp_password; // managed (masked) via the notifications settings endpoint
  res.json({ settings });
});

router.put('/settings', requireCapability('admin.settings'), (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', requireCapability('admin.users'), (req, res) => {
  const users = all(`${userSelect} ORDER BY u.name`).map((u) => ({ ...u, company_ids: companies.assignedCompanyIds(u.id) }));
  res.json({ users });
});

router.post('/users', requireCapability('admin.users'), (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' });

  // An admin-supplied password must satisfy the policy. When none is given we issue a temporary
  // password and force a change at first login (so a throwaway temp isn't policy-checked).
  const supplied = req.body.password;
  if (supplied) passwordPolicy.validatePassword(supplied, { name: req.body.name, email: req.body.email });
  const rawPassword = supplied || 'ChangeMe123!';
  const mustChange = req.body.must_change_password || !supplied ? 1 : 0;

  const created = now();
  const hash = bcrypt.hashSync(rawPassword, 12);
  const result = run(
    'INSERT INTO users (team_id, name, email, password_hash, role, status, password_changed_at, must_change_password, 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,
      hash,
      req.body.role || 'viewer',
      req.body.status || 'active',
      created,
      mustChange,
      created,
      created
    ]
  );
  passwordPolicy.recordPassword(result.lastInsertRowid, hash);
  // Assign company access: the supplied list, else default to the creating admin's active company.
  const companyIds = Array.isArray(req.body.company_ids) && req.body.company_ids.length ? req.body.company_ids : (req.companyId ? [req.companyId] : []);
  companies.setUserCompanies(result.lastInsertRowid, companyIds, req.user.id);
  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', requireCapability('admin.users'), (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' });
  }

  // Validate before any write so a rejected password leaves the row untouched.
  if (req.body.password) {
    passwordPolicy.validatePassword(req.body.password, {
      id: Number(req.params.id),
      name: req.body.name || before.name,
      email: req.body.email || before.email
    });
  }

  const nextMustChange = req.body.must_change_password !== undefined
    ? (req.body.must_change_password ? 1 : 0)
    : before.must_change_password;

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

  if (req.body.password) {
    const hash = bcrypt.hashSync(req.body.password, 12);
    // Admin-set password forces a change at next login unless explicitly cleared.
    const forceChange = req.body.must_change_password === false ? 0 : 1;
    run('UPDATE users SET password_hash = ?, password_changed_at = ?, must_change_password = ?, updated_at = ? WHERE id = ?', [
      hash,
      updated,
      forceChange,
      updated,
      req.params.id
    ]);
    passwordPolicy.recordPassword(req.params.id, hash);
  }

  if (req.body.company_ids !== undefined) {
    companies.setUserCompanies(req.params.id, req.body.company_ids, req.user.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', requireCapability('admin.users'), (req, res) => {
  res.json({ teams: all('SELECT * FROM teams ORDER BY name') });
});

router.post('/teams', requireCapability('admin.users'), (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.put('/teams/:id', requireCapability('admin.users'), (req, res) => {
  const before = one('SELECT * FROM teams WHERE id = ?', [req.params.id]);
  if (!before) return res.status(404).json({ error: 'Team not found' });
  run('UPDATE teams SET name = ?, description = ? WHERE id = ?', [
    req.body.name || before.name,
    req.body.description ?? before.description,
    req.params.id
  ]);
  audit(req.user.id, 'update', 'team', req.params.id, before, req.body);
  return res.json({ team: one('SELECT * FROM teams WHERE id = ?', [req.params.id]) });
});

router.delete('/teams/:id', requireCapability('admin.users'), (req, res) => {
  const before = one('SELECT * FROM teams WHERE id = ?', [req.params.id]);
  if (!before) return res.status(404).json({ error: 'Team not found' });
  const memberCount = one('SELECT COUNT(*) AS count FROM users WHERE team_id = ?', [req.params.id]).count;
  if (memberCount) {
    return res.status(400).json({ error: `Reassign the ${memberCount} user(s) on this team before deleting it` });
  }
  run('DELETE FROM teams WHERE id = ?', [req.params.id]);
  audit(req.user.id, 'delete', 'team', req.params.id, before, null);
  return res.status(204).end();
});

router.get('/access-control', requireCapability('admin.users'), (req, res) => {
  res.json({ roles: listRoles(), capabilities: CAPABILITIES });
});

// ---- Roles (capability sets, custom roles allowed) --------------------------

router.get('/roles', requireCapability('admin.roles'), (req, res) => {
  res.json({ roles: listRoles(), capabilities: CAPABILITIES });
});

router.post('/roles', requireCapability('admin.roles'), (req, res, next) => {
  try {
    res.status(201).json({ role: createRole(req.body, req.user.id) });
  } catch (error) {
    next(error);
  }
});

router.put('/roles/:key', requireCapability('admin.roles'), (req, res) => {
  const role = updateRole(req.params.key, req.body, req.user.id);
  if (!role) return res.status(404).json({ error: 'Role not found' });
  return res.json({ role });
});

router.delete('/roles/:key', requireCapability('admin.roles'), (req, res) => {
  const result = deleteRole(req.params.key, req.user.id);
  if (!result.ok) return res.status(result.status).json({ error: result.error });
  return res.status(204).end();
});

// ---- Account lockout --------------------------------------------------------

router.post('/users/:id/unlock', requireCapability('admin.users'), (req, res) => {
  const user = publicAdminUser(req.params.id);
  if (!user) return res.status(404).json({ error: 'User not found' });
  passwordPolicy.unlock(req.params.id, req.user.id);
  return res.json({ user: publicAdminUser(req.params.id) });
});

// ---- Password & lockout policy ----------------------------------------------

router.get('/password-policy', requireCapability('admin.security'), (req, res) => {
  const policy = passwordPolicy.getPolicy();
  res.json({ policy, rules: passwordPolicy.describe(policy) });
});

router.put('/password-policy', requireCapability('admin.security'), (req, res) => {
  const policy = passwordPolicy.savePolicy(req.body.policy || req.body, req.user.id);
  res.json({ policy, rules: passwordPolicy.describe(policy) });
});

// ---- Activity & audit trail -------------------------------------------------

function auditFilters(query) {
  return {
    actor: query.actor || null,
    action: query.action || null,
    entity_type: query.entity_type || null,
    from: query.from || null,
    to: query.to || null,
    q: query.q || null
  };
}

router.get('/audit-logs', requireCapability('admin.audit'), (req, res) => {
  const result = auditTrail.query(auditFilters(req.query), { page: req.query.page, pageSize: req.query.pageSize });
  res.json({ ...result, facets: auditTrail.facets() });
});

// ---- Application / event logs (Winston) -------------------------------------

router.get('/app-logs', requireCapability('admin.logs'), (req, res) => {
  res.json(appLogs.readLogs({ category: req.query.category || null, level: req.query.level || null, q: req.query.q || null }, req.query.limit));
});

router.get('/audit-logs/export', requireCapability('admin.audit'), (req, res) => {
  const rows = auditTrail.queryAll(auditFilters(req.query));
  audit(req.user.id, 'export', 'audit_logs', 'csv', null, { count: rows.length, filters: auditFilters(req.query) });
  res.setHeader('Content-Type', 'text/csv; charset=utf-8');
  res.setHeader('Content-Disposition', `attachment; filename="audit-trail-${now().slice(0, 10)}.csv"`);
  res.send(auditTrail.toCsv(rows));
});

module.exports = router;
