'use strict';

const express = require('express');
const { pool } = require('../db');
const { generateToken, hashToken, verifyPassword } = require('../security');
const { normalizeUsername, requestIp, asyncHandler } = require('../utils');
const { requireUser, requireAdmin } = require('../auth');
const { writeAudit } = require('../audit');

const router = express.Router();

router.post('/login', asyncHandler(async (req, res) => {
  const username = normalizeUsername(req.body?.username);
  const password = String(req.body?.password || '');
  if (!username || !password) return res.status(400).json({ message: 'أدخل اسم المستخدم وكلمة المرور.' });

  const [rows] = await pool.execute('SELECT id, username, password_hash, category FROM users WHERE username = ? LIMIT 1', [username]);
  const user = rows[0];
  if (!user || !(await verifyPassword(password, user.password_hash))) {
    await writeAudit({ req, actorType: 'system', actorName: username, actionKey: 'user_login_failed' });
    return res.status(401).json({ message: 'اسم المستخدم أو كلمة المرور غير صحيحة.' });
  }

  const token = generateToken();
  await pool.execute(
    'INSERT INTO user_sessions (user_id, token_hash, user_agent, ip_address) VALUES (?, ?, ?, ?)',
    [user.id, hashToken(token), String(req.headers['user-agent'] || '').slice(0, 500) || null, requestIp(req)],
  );
  const [permissionRows] = await pool.execute('SELECT menu_key FROM user_permissions WHERE user_id = ? ORDER BY menu_key', [user.id]);
  const payload = {
    id: user.id,
    username: user.username,
    category: user.category,
    permissions: permissionRows.map((row) => row.menu_key),
  };
  await writeAudit({ req, actorType: 'user', actorId: user.id, actorName: user.username, actionKey: 'user_login' });
  return res.json({ token, user: payload });
}));

router.get('/me', requireUser, (req, res) => res.json({ user: req.user }));

router.post('/logout', requireUser, asyncHandler(async (req, res) => {
  await pool.execute('DELETE FROM user_sessions WHERE token_hash = ?', [req.authTokenHash]);
  await writeAudit({ req, actorType: 'user', actorId: req.user.id, actorName: req.user.username, actionKey: 'user_logout' });
  res.json({ message: 'تم تسجيل الخروج.' });
}));

router.post('/admin/login', asyncHandler(async (req, res) => {
  const username = normalizeUsername(req.body?.username);
  const password = String(req.body?.password || '');
  if (!username || !password) return res.status(400).json({ message: 'أدخل اسم المستخدم وكلمة المرور.' });

  const [rows] = await pool.execute('SELECT id, username, password_hash FROM admins WHERE username = ? LIMIT 1', [username]);
  const admin = rows[0];
  if (!admin || !(await verifyPassword(password, admin.password_hash))) {
    await writeAudit({ req, actorType: 'system', actorName: username, actionKey: 'admin_login_failed' });
    return res.status(401).json({ message: 'بيانات دخول الأدمن غير صحيحة.' });
  }

  const token = generateToken();
  await pool.execute(
    'INSERT INTO admin_sessions (admin_id, token_hash, user_agent, ip_address) VALUES (?, ?, ?, ?)',
    [admin.id, hashToken(token), String(req.headers['user-agent'] || '').slice(0, 500) || null, requestIp(req)],
  );
  await writeAudit({ req, actorType: 'admin', actorId: admin.id, actorName: admin.username, actionKey: 'admin_login' });
  res.json({ token, admin: { id: admin.id, username: admin.username } });
}));

router.get('/admin/me', requireAdmin, (req, res) => res.json({ admin: req.admin }));

router.post('/admin/logout', requireAdmin, asyncHandler(async (req, res) => {
  await pool.execute('DELETE FROM admin_sessions WHERE token_hash = ?', [req.authTokenHash]);
  await writeAudit({ req, actorType: 'admin', actorId: req.admin.id, actorName: req.admin.username, actionKey: 'admin_logout' });
  res.json({ message: 'تم تسجيل الخروج.' });
}));

module.exports = router;
