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

const router = express.Router();

router.get('/templates', (req, res) => {
  const templates = all('SELECT * FROM asset_templates ORDER BY name').map((row) => ({
    ...row,
    defaults: parseJson(row.defaults, {}),
    custom_fields: parseJson(row.custom_fields, [])
  }));
  res.json({ templates });
});

router.post('/templates', requireRole('admin', 'finance'), (req, res) => {
  const created = now();
  const result = run(
    'INSERT INTO asset_templates (name, description, defaults, custom_fields, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)',
    [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]) });
});

module.exports = router;
