const express = require('express');
const { all, audit, json, now, one, parseJson, run } = require('../db');
const { requireCapability } = require('../middleware/auth');

const router = express.Router();

router.get('/templates', (req, res) => {
  const templates = all(
    `SELECT t.*, (SELECT COUNT(*) FROM assets a WHERE a.template_id = t.id) AS asset_count
     FROM asset_templates t WHERE t.entity_id = ? ORDER BY t.name`,
    [req.companyId]
  ).map((row) => ({
    ...row,
    defaults: parseJson(row.defaults, {}),
    custom_fields: parseJson(row.custom_fields, [])
  }));
  res.json({ templates });
});

router.post('/templates', requireCapability('config.manage'), (req, res) => {
  const created = now();
  const result = run(
    'INSERT INTO asset_templates (entity_id, name, description, defaults, custom_fields, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
    [req.companyId, req.body.name, req.body.description || null, json(req.body.defaults || {}), json(req.body.custom_fields || []), created, created]
  );
  audit(req.user.id, 'create', 'asset_template', result.lastInsertRowid, null, req.body);
  res.status(201).json({ template: one('SELECT * FROM asset_templates WHERE id = ?', [result.lastInsertRowid]) });
});

router.put('/templates/:id', requireCapability('config.manage'), (req, res) => {
  const before = one('SELECT * FROM asset_templates WHERE id = ? AND entity_id = ?', [req.params.id, req.companyId]);
  if (!before) return res.status(404).json({ error: 'Template not found' });
  run(
    'UPDATE asset_templates SET name = ?, description = ?, defaults = ?, custom_fields = ?, updated_at = ? WHERE id = ?',
    [
      req.body.name ?? before.name,
      req.body.description ?? before.description,
      json(req.body.defaults || {}),
      json(req.body.custom_fields || []),
      now(),
      req.params.id
    ]
  );
  audit(req.user.id, 'update', 'asset_template', req.params.id, before, req.body);
  return res.json({ template: one('SELECT * FROM asset_templates WHERE id = ?', [req.params.id]) });
});

// Deleting a template unlinks it from any assets (their stored field values are kept)
// and removes it from the picker for future assets.
router.delete('/templates/:id', requireCapability('config.manage'), (req, res) => {
  const before = one('SELECT * FROM asset_templates WHERE id = ? AND entity_id = ?', [req.params.id, req.companyId]);
  if (!before) return res.status(404).json({ error: 'Template not found' });
  const affected = one('SELECT COUNT(*) AS c FROM assets WHERE template_id = ?', [req.params.id]).c;
  run('UPDATE assets SET template_id = NULL, updated_at = ? WHERE template_id = ?', [now(), req.params.id]);
  run('DELETE FROM asset_templates WHERE id = ?', [req.params.id]);
  audit(req.user.id, 'delete', 'asset_template', req.params.id, before, { unlinked_assets: affected });
  return res.json({ deleted: true, unlinked_assets: affected });
});

module.exports = router;
