// Templates + Records route. Template = virtual table def; record = composed entries.
import { Hono } from 'hono';
import type { Bindings } from '../types';
import { createTemplate, getTemplate, listTemplates, updateTemplate } from '../actions/record-crud';

export const templateRoutes = new Hono<{ Bindings: Bindings }>();

templateRoutes.post('/', async (c) => {
  const body = await c.req.json().catch(() => null);
  if (!body || !body.name || !Array.isArray(body.slots)) {
    return c.json({ success: false, error: 'name and slots[] required' }, 400);
  }
  const tpl = await createTemplate(c.env.DB, body);
  return c.json({ success: true, template: tpl });
});

templateRoutes.get('/', async (c) => {
  const templates = await listTemplates(c.env.DB);
  return c.json({ success: true, templates, count: templates.length });
});

templateRoutes.get('/:idOrName', async (c) => {
  const tpl = await getTemplate(c.env.DB, c.req.param('idOrName'));
  if (!tpl) return c.json({ success: false, error: 'not found' }, 404);
  return c.json({ success: true, template: tpl });
});

templateRoutes.patch('/:id', async (c) => {
  const body = await c.req.json().catch(() => ({}));
  const tpl = await updateTemplate(c.env.DB, c.req.param('id'), body);
  if (!tpl) return c.json({ success: false, error: 'not found' }, 404);
  return c.json({ success: true, template: tpl });
});
