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

const ps = (cmd, timeout = 30000) =>
  execSync(`powershell -ExecutionPolicy Bypass -Command "${cmd}"`, { timeout }).toString().trim();

// ── List tasks ─────────────────────────────────────────
router.get('/', authMw, (req, res) => {
  try {
    const raw = ps(`
      Get-ScheduledTask | Where-Object { $_.TaskPath -notlike '\\Microsoft\\*' } |
      ForEach-Object {
        $info = $_ | Get-ScheduledTaskInfo -ErrorAction SilentlyContinue
        [PSCustomObject]@{
          Name        = $_.TaskName
          Path        = $_.TaskPath
          State       = $_.State.ToString()
          Description = $_.Description
          LastRun     = if($info.LastRunTime -and $info.LastRunTime.Year -gt 1999){ $info.LastRunTime.ToString('yyyy-MM-dd HH:mm:ss') } else { 'Never' }
          NextRun     = if($info.NextRunTime -and $info.NextRunTime.Year -gt 1999){ $info.NextRunTime.ToString('yyyy-MM-dd HH:mm:ss') } else { '-' }
          LastResult  = $info.LastTaskResult
        }
      } | ConvertTo-Json -Depth 2
    `, 30000);
    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 }); }
});

// ── Get task details ───────────────────────────────────
router.get('/:name', authMw, (req, res) => {
  const name = req.params.name;
  try {
    const raw = ps(`
      $t = Get-ScheduledTask -TaskName '${name}' -ErrorAction Stop
      $triggers = $t.Triggers | ForEach-Object {
        [PSCustomObject]@{ Type=$_.CimClass.CimClassName; Enabled=$_.Enabled; Details=($_ | ConvertTo-Json -Depth 2 -Compress) }
      }
      $actions = $t.Actions | ForEach-Object {
        [PSCustomObject]@{ Type=$_.CimClass.CimClassName; Execute=$_.Execute; Arguments=$_.Arguments; WorkingDirectory=$_.WorkingDirectory }
      }
      [PSCustomObject]@{ Name=$t.TaskName; Description=$t.Description; Triggers=@($triggers); Actions=@($actions) } | ConvertTo-Json -Depth 4
    `);
    res.json(JSON.parse(raw));
  } catch(e) { res.status(500).json({ error: e.message }); }
});

// ── Create task ────────────────────────────────────────
router.post('/', authMw, (req, res) => {
  const { name, description, execute, arguments: args, workingDir,
          triggerType, triggerTime, triggerDay, triggerInterval } = req.body;

  if (!name || !execute) return res.status(400).json({ error: 'Name and execute are required' });
  if (!/^[\w\s\-\.]+$/.test(name)) return res.status(400).json({ error: 'Invalid task name' });

  try {
    // Build action
    const actionArgs = args ? `-Argument '${args.replace(/'/g,"''")}'` : '';
    const wdArgs     = workingDir ? `-WorkingDirectory '${workingDir}'` : '';
    const action     = `$action = New-ScheduledTaskAction -Execute '${execute.replace(/'/g,"''")}' ${actionArgs} ${wdArgs}`;

    // Build trigger
    let trigger = '';
    switch (triggerType) {
      case 'once':
        trigger = `$trigger = New-ScheduledTaskTrigger -Once -At '${triggerTime || '00:00'}'`;
        break;
      case 'daily':
        trigger = `$trigger = New-ScheduledTaskTrigger -Daily -At '${triggerTime || '00:00'}'`;
        break;
      case 'weekly':
        trigger = `$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek ${triggerDay || 'Monday'} -At '${triggerTime || '00:00'}'`;
        break;
      case 'hourly':
        trigger = `$trigger = New-ScheduledTaskTrigger -RepetitionInterval (New-TimeSpan -Hours ${parseInt(triggerInterval)||1}) -Once -At '${triggerTime || (new Date().toISOString().slice(0,16).replace('T',' '))}'`;
        break;
      case 'startup':
        trigger = `$trigger = New-ScheduledTaskTrigger -AtStartup`;
        break;
      case 'login':
        trigger = `$trigger = New-ScheduledTaskTrigger -AtLogOn`;
        break;
      default:
        trigger = `$trigger = New-ScheduledTaskTrigger -Daily -At '00:00'`;
    }

    const desc = description ? `-Description '${description.replace(/'/g,"''")}'` : '';
    ps(`
      ${action}
      ${trigger}
      $settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Hours 1) -MultipleInstances IgnoreNew
      Register-ScheduledTask -TaskName '${name}' ${desc} -Action $action -Trigger $trigger -Settings $settings -RunLevel Highest -Force
    `);
    res.json({ ok: true });
  } catch(e) { res.status(500).json({ error: e.message }); }
});

// ── Enable / disable / run / delete ───────────────────
router.post('/:name/enable', authMw, (req, res) => {
  try { ps(`Enable-ScheduledTask -TaskName '${req.params.name}'`); res.json({ ok: true }); }
  catch(e) { res.status(500).json({ error: e.message }); }
});

router.post('/:name/disable', authMw, (req, res) => {
  try { ps(`Disable-ScheduledTask -TaskName '${req.params.name}'`); res.json({ ok: true }); }
  catch(e) { res.status(500).json({ error: e.message }); }
});

router.post('/:name/run', authMw, (req, res) => {
  try { ps(`Start-ScheduledTask -TaskName '${req.params.name}'`); res.json({ ok: true }); }
  catch(e) { res.status(500).json({ error: e.message }); }
});

router.delete('/:name', authMw, (req, res) => {
  try { ps(`Unregister-ScheduledTask -TaskName '${req.params.name}' -Confirm:$false`); res.json({ ok: true }); }
  catch(e) { res.status(500).json({ error: e.message }); }
});

module.exports = router;