// GET /components/:id — 取得零件最優版本合約
// GET /components/:id/versions — 取得所有版本清單（含評分）
// GET /components/search?q=... — 語意搜尋零件
// Requirements: 12.2, 12.3

import { Hono } from 'hono';
import type { Bindings } from '../types';
import { getComponent, getComponentVersions, searchComponents } from '../actions/queryComponents';

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

// 語意搜尋（必須在 /:id 之前，避免 "search" 被當作 id）
app.get('/search', async c => {
  const q = c.req.query('q');
  if (!q || q.trim() === '') {
    return c.json({ success: false, error: 'q 參數必填' }, 400);
  }

  const results = await searchComponents(q.trim(), c.env);
  return c.json({ success: true, data: { results, count: results.length } });
});

// 取得所有版本
app.get('/:id/versions', async c => {
  const id = c.req.param('id');
  const versions = await getComponentVersions(id, c.env);
  if (versions.length === 0) {
    return c.json({ success: false, error: `零件 ${id} 不存在` }, 404);
  }
  return c.json({ success: true, data: { versions, count: versions.length } });
});

// 取得最優版本
app.get('/:id', async c => {
  const id = c.req.param('id');
  const component = await getComponent(id, c.env);
  if (!component) {
    return c.json({ success: false, error: `零件 ${id} 不存在` }, 404);
  }
  return c.json({ success: true, data: component });
});

export default app;
