import { camelJob } from '../models/mappers.js';
import { createRunPlan, deleteRunPlan, listRunPlans, loadVisibleRunPlan, updateRunPlan } from '../models/runPlanModel.js';
import { executeRunPlan } from '../services/powershellRunner.js';

export function index(req, res) {
  res.json(listRunPlans(req.user.id));
}

export function create(req, res) {
  res.status(201).json(createRunPlan(req.body, req.user.id));
}

export function show(req, res) {
  const runplan = loadVisibleRunPlan(req.params.id, req.user.id);
  if (!runplan) return res.status(404).json({ error: 'RunPlan not found' });
  res.json(runplan);
}

export function update(req, res) {
  const runplan = updateRunPlan(req.params.id, req.body, req.user.id);
  if (!runplan) return res.status(404).json({ error: 'RunPlan not found' });
  res.json(runplan);
}

export function destroy(req, res) {
  deleteRunPlan(req.params.id, req.user.id);
  res.status(204).end();
}

export function execute(req, res) {
  // Execution remains an API concern; Vue only requests a RunPlan launch.
  const runplan = loadVisibleRunPlan(req.params.id, req.user.id);
  if (!runplan) return res.status(404).json({ error: 'RunPlan not found' });
  try {
    res.status(202).json(camelJob(executeRunPlan(req.params.id, req.user.id)));
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
}
