// GET /v1/products/:id  — public, one product or 404.
//
// `:id` is a PATH param — the desugar re-derives it from the matched pattern
// into `params`. A handler `throw { status, message }` maps to that HTTP code;
// anything else → 500.

import { defineRestRoute } from '@voltro/protocol/rest'
import { Schema } from 'effect'
import { eq } from '@voltro/database'
import type { DataStore } from '@voltro/runtime'
import { database } from '../../database/schema'
import { Product, toProduct } from '../../lib/product'

export default defineRestRoute({
  method: 'GET',
  path:   '/v1/products/:id',
  input: Schema.Struct({
    params: Schema.Struct({ id: Schema.NonEmptyString }),
  }),
  output:  Product,
  summary: 'Get a product by id',
  handler: async ({ params }, ctx) => {
    const store = ctx.store as DataStore
    const rows = await store.query(database.products.where(eq('id', params.id)).limit(1).descriptor)
    const row = rows[0]
    if (row === undefined) throw { status: 404, message: `product '${params.id}' not found` }
    return toProduct(row as Record<string, unknown>)
  },
})
