/**
 * {{titleCase name}} API
 *
 * Environment variables injected by mesh link():
 * - PORT: Server port (default: 3000)
{{#if database}}
 * - DATABASE_URL: PostgreSQL connection string
{{/if}}
{{#if temporal}}
 * - TEMPORAL_ADDRESS, TEMPORAL_NAMESPACE, TEMPORAL_TASK_QUEUE
{{/if}}
{{#if bucket}}
 * - UPLOADS_BUCKET, UPLOADS_REGION
{{/if}}
 */

import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { createLogger, requestLogger } from "@mesh-tech/logger";
{{#if temporal}}
import { createTemporalClient } from "@mesh-tech/app-kit/temporal-client";
{{/if}}

const PORT = parseInt(process.env.PORT ?? "3000", 10);
// Every service logs through @mesh-tech/logger (the Mesh app contract, gate
// 0.4): structured, masked, trace-correlated lines the Hub can search.
const log = createLogger({ service: "{{name}}-api" });
const app = new Hono();
app.use("*", requestLogger(log));

{{#if temporal}}
const { withClient } = await createTemporalClient();
{{/if}}

// Health check
app.get("/health", (c) => c.json({ status: "ok" }));

// Hello endpoint
app.get("/", (c) => c.json({ message: "{{titleCase name}} API" }));

{{#if temporal}}
// Start a workflow
app.post("/workflow", async (c) => {
  const body = await c.req.json<{ name: string }>();
  const result = await withClient(async (client) => {
    const handle = await client.workflow.start("greetingWorkflow", {
      taskQueue: process.env.TEMPORAL_TASK_QUEUE ?? "{{name}}",
      workflowId: `greeting-${Date.now()}`,
      args: [body.name ?? "world"],
    });
    return handle.result();
  });
  return c.json({ result });
});
{{/if}}

// Start server
serve({ fetch: app.fetch, port: PORT, hostname: "0.0.0.0" }, (info) => {
  log.info({ port: info.port }, "{{titleCase name}} API listening");
});
