// Records route — structured records (entry_values composed by a template).
import { Hono } from 'hono';
import type { Bindings } from '../types';
import { createRecord, getRecord, searchByTemplate, updateRecord } from '../actions/record-crud';

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

// POST /records — { template, values:{slot:content}, owner_id? }
recordRoutes.post('/', async (c) => {
  const body = await c.req.json().catch(() => null);
  if (!body || !body.template || !body.values) {
    return c.json({ success: false, error: 'template and values required' }, 400);
  }
  try {
    const rec = await createRecord(c.env.DB, body);
    return c.json({ success: true, record: rec });
  } catch (e) {
    return c.json({ success: false, error: e instanceof Error ? e.message : String(e) }, 400);
  }
});

// GET /records/by-template/:template — list records of a template
recordRoutes.get('/by-template/:template', async (c) => {
  const records = await searchByTemplate(c.env.DB, c.req.param('template'), c.req.query('owner_id') || undefined);
  return c.json({ success: true, records, count: records.length });
});

// GET /records/:recordId
recordRoutes.get('/:recordId', async (c) => {
  const rec = await getRecord(c.env.DB, c.req.param('recordId'));
  if (!rec) return c.json({ success: false, error: 'not found' }, 404);
  return c.json({ success: true, record: rec });
});

// PATCH /records/:recordId — { values:{slot:content} } update existing record slot values
// (mira-dissolve T2.1 / issue #6; deprecate = flip a slot value, append-only tables untouched).
recordRoutes.patch('/:recordId', async (c) => {
  const body = await c.req.json().catch(() => null);
  if (!body || !body.values || typeof body.values !== 'object') {
    return c.json({ success: false, error: 'values required' }, 400);
  }
  try {
    const rec = await updateRecord(c.env.DB, c.req.param('recordId'), body.values);
    if (!rec) return c.json({ success: false, error: 'not found' }, 404);
    return c.json({ success: true, record: rec });
  } catch (e) {
    return c.json({ success: false, error: e instanceof Error ? e.message : String(e) }, 400);
  }
});
