const express = require('express');
const { z } = require('zod');
const service = require('../instrumentConfig/service');

const router = express.Router();

const schema = z.object({
  instrument_id: z.string().min(1),
  connector: z.enum(['http-json', 'hl7-tcp', 'astm-serial']),
  enabled: z.boolean().optional().default(true),
  config: z.record(z.any()).optional()
});

router.get('/', async (req, res) => {
  res.json(service.list());
});

router.get('/:id', async (req, res) => {
  const entry = service.get(req.params.id);
  if (!entry) {
    return res.status(404).json({ error: 'not found' });
  }
  res.json(entry);
});

router.post('/', express.json(), async (req, res) => {
  try {
    const payload = schema.parse(req.body);
    const saved = await service.upsert(payload);
    res.status(201).json(saved);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

module.exports = { router };
