const express = require('express');
const { requireCapability } = require('../middleware/auth');
const {
  assetPmRows,
  attachPlan,
  completePm,
  createPlan,
  deletePlan,
  detachAssetPm,
  getCompletion,
  getPlan,
  getSettings,
  listCompletions,
  listPlans,
  logReading,
  recomputeAllSchedules,
  saveSettings,
  updateAssetPm,
  updatePlan
} = require('../services/pm');

const router = express.Router();
const planEditor = requireCapability('pm.manage'); // create/edit PM plan templates & defaults
const assetPm = requireCapability('pm.complete'); // attach to assets & complete services

// PM plan templates
router.get('/pm-plans', (req, res) => {
  res.json({ plans: listPlans(req.companyId) });
});

router.get('/pm-plans/:id', (req, res) => {
  const plan = getPlan(req.params.id);
  if (!plan) return res.status(404).json({ error: 'PM plan not found' });
  return res.json({ plan });
});

router.post('/pm-plans', planEditor, (req, res) => {
  res.status(201).json({ plan: createPlan(req.body, req.user.id, req.companyId) });
});

router.put('/pm-plans/:id', planEditor, (req, res) => {
  const plan = updatePlan(req.params.id, req.body, req.user.id);
  if (!plan) return res.status(404).json({ error: 'PM plan not found' });
  return res.json({ plan });
});

router.delete('/pm-plans/:id', planEditor, (req, res) => {
  if (!deletePlan(req.params.id, req.user.id)) return res.status(404).json({ error: 'PM plan not found' });
  return res.status(204).end();
});

// PM defaults (readable by any authenticated user; pm.manage can change)
router.get('/pm-settings', (req, res) => {
  res.json({ settings: getSettings() });
});

router.put('/pm-settings', planEditor, (req, res) => {
  res.json({ settings: saveSettings(req.body, req.user.id) });
});

// Manually run the schedule recompute now ("Run now" in PM settings).
router.post('/pm-recompute', planEditor, (req, res) => {
  res.json({ result: recomputeAllSchedules(req.user.id), settings: getSettings() });
});

// Completed PM forms
router.get('/pm-completions', (req, res) => {
  res.json({ completions: listCompletions(req.query) });
});

router.get('/pm-completions/:id', (req, res) => {
  const completion = getCompletion(req.params.id);
  if (!completion) return res.status(404).json({ error: 'Completion not found' });
  return res.json({ completion });
});

// Per-asset PM schedules
router.get('/assets/:id/pm', (req, res) => {
  res.json({ pm: assetPmRows(req.params.id) });
});

router.post('/assets/:id/pm', assetPm, (req, res) => {
  res.status(201).json({ pm: attachPlan(req.params.id, req.body, req.user.id) });
});

router.put('/assets/:id/pm/:apId', assetPm, (req, res) => {
  const pm = updateAssetPm(req.params.id, req.params.apId, req.body, req.user.id);
  if (!pm) return res.status(404).json({ error: 'PM schedule not found' });
  return res.json({ pm });
});

router.delete('/assets/:id/pm/:apId', assetPm, (req, res) => {
  if (!detachAssetPm(req.params.id, req.params.apId, req.user.id)) return res.status(404).json({ error: 'PM schedule not found' });
  return res.status(204).end();
});

router.post('/assets/:id/pm/:apId/complete', assetPm, (req, res) => {
  const pm = completePm(req.params.id, req.params.apId, req.body, req.user.id);
  if (!pm) return res.status(404).json({ error: 'PM schedule not found' });
  return res.json({ pm });
});

// Log a standalone usage meter reading (quick-log / inspection) and recompute the schedule.
router.post('/assets/:id/pm/:apId/readings', assetPm, (req, res, next) => {
  try {
    const pm = logReading(req.params.id, req.params.apId, req.body, req.user.id);
    if (!pm) return res.status(404).json({ error: 'PM schedule not found' });
    return res.json({ pm });
  } catch (error) {
    return next(error);
  }
});

module.exports = router;
