'use strict';

const express = require('express');
const router = express.Router();
const security = require('../security/securityStore');
const { requirePermission } = require('../middleware/permissions');

router.get('/permissions', requirePermission('security.profiles.view'), (_req, res) => {
  const state = security.loadState();
  res.json({ ok: true, permissions: state.permissions });
});

router.get('/profiles', requirePermission('security.profiles.view'), (_req, res) => {
  const state = security.loadState();
  res.json({ ok: true, profiles: state.profiles, permissions: state.permissions });
});

router.post('/profiles', requirePermission('security.profiles.manage'), (req, res) => {
  try {
    res.json({ ok: true, profile: security.upsertProfile(req.body || {}, req.user) });
  } catch (err) {
    res.status(400).json({ ok: false, error: err.message });
  }
});

router.delete('/profiles/:id', requirePermission('security.profiles.manage'), (req, res) => {
  const result = security.deleteProfile(req.params.id, req.user);
  res.status(result.ok ? 200 : 400).json(result);
});

router.get('/users', requirePermission('security.users.view'), (_req, res) => {
  res.json({ ok: true, ...security.loginConfig() });
});

router.get('/me', (req, res) => {
  const userId = req.user?.id || req.user?.username;
  if (!userId || req.user?.tipo === 'api_key' || req.user?.tipo === 'local') {
    return res.status(403).json({ ok: false, error: 'Perfil de usuario no disponible para esta sesion.' });
  }
  const state = security.loadState();
  const user = state.users[userId];
  if (!user) return res.status(404).json({ ok: false, error: 'Usuario no encontrado.' });
  res.json({ ok: true, user: security.publicUser(userId, user, state) });
});

router.put('/me', (req, res) => {
  const userId = req.user?.id || req.user?.username;
  if (!userId || req.user?.tipo === 'api_key' || req.user?.tipo === 'local') {
    return res.status(403).json({ ok: false, error: 'Perfil de usuario no disponible para esta sesion.' });
  }
  const result = security.updateOwnProfile(userId, req.body || {}, req.user);
  res.status(result.ok ? 200 : 400).json(result);
});

router.post('/users', requirePermission('security.users.manage'), (req, res) => {
  try {
    res.json({ ok: true, user: security.upsertUser(req.body || {}, req.user) });
  } catch (err) {
    res.status(400).json({ ok: false, code: err.code || 'user_save_failed', error: err.message });
  }
});

router.post('/users/:id/profiles', requirePermission('security.users.manage'), (req, res) => {
  const result = security.assignProfiles(req.params.id, req.body?.profile_ids || [], req.user);
  res.status(result.ok ? 200 : 400).json(result);
});

router.post('/password-policy/validate', requirePermission('security.users.manage'), (req, res) => {
  res.json(security.validatePassword(req.body?.password || ''));
});

module.exports = router;
