const express      = require('express');
const { execSync } = require('child_process');
const fs           = require('fs');
const path         = require('path');
const router       = express.Router();
const authMw       = require('../middleware/auth');

const ps = cmd => execSync(`powershell -ExecutionPolicy Bypass -Command "${cmd}"`, { timeout: 60000 }).toString().trim();
const CRASH_LOG = path.join(__dirname, '../data/crash.log');

// ── Windows Event Logs ─────────────────────────────────
router.get('/', authMw, (req, res) => {
  const logName = ['Application','System','Security'].includes(req.query.log) ? req.query.log : 'Application';
  const count   = Math.min(parseInt(req.query.count) || 100, 500);
  const level   = req.query.level;
  try {
    let cmd = `Get-EventLog -LogName ${logName} -Newest ${count}`;
    if (level && level !== 'All') cmd += ` -EntryType ${level}`;
    cmd += ` | Select-Object TimeGenerated,EntryType,Source,EventID,@{N='Message';E={$_.Message.Substring(0,[math]::Min($_.Message.Length,250))}} | ConvertTo-Json`;
    const raw = ps(cmd);
    if (!raw) return res.json([]);
    const list = JSON.parse(raw);
    res.json(Array.isArray(list) ? list : [list]);
  } catch(e) { res.status(500).json({ error: e.message }); }
});

// ── Crash / Panel Logs ─────────────────────────────────
router.get('/crash', authMw, (req, res) => {
  try {
    if (!fs.existsSync(CRASH_LOG)) return res.json([]);
    const lines = fs.readFileSync(CRASH_LOG, 'utf8')
      .split('\n')
      .filter(Boolean)
      .map(l => { try { return JSON.parse(l); } catch { return null; } })
      .filter(Boolean)
      .reverse(); // newest first
    res.json(lines);
  } catch(e) { res.status(500).json({ error: e.message }); }
});

// ── Clear crash log ────────────────────────────────────
router.delete('/crash', authMw, (req, res) => {
  try {
    if (fs.existsSync(CRASH_LOG)) fs.writeFileSync(CRASH_LOG, '');
    res.json({ ok: true });
  } catch(e) { res.status(500).json({ error: e.message }); }
});

module.exports = router;