/**
 * StyloBridge API — Cloudflare Worker
 *
 * Endpoints:
 *   POST /api/checkout     — Create Stripe Checkout session
 *   POST /api/webhook      — Stripe webhook (sign token + email)
 *   POST /api/demo-token   — Ad-hoc demo token generation (password-protected)
 *   POST /api/demo-request — Contact form submission
 */

import { Hono } from "hono";
import type { Env } from "./env.d";
import { corsMiddleware } from "./lib/cors";
import { handleCheckout } from "./endpoints/checkout";
import { handleDemoRequest } from "./endpoints/demo-request";
import { handleDemoToken } from "./endpoints/demo-token";
import { handleWebhook } from "./endpoints/webhook";

const app = new Hono();

// Security headers on all responses
app.use("*", async (c, next) => {
  await next();
  c.res.headers.set("X-Content-Type-Options", "nosniff");
  c.res.headers.set("X-Frame-Options", "DENY");
  c.res.headers.set(
    "Content-Security-Policy",
    "default-src 'none'; frame-ancestors 'none'"
  );
  c.res.headers.set("Referrer-Policy", "no-referrer");
});

// CORS for all routes (website is on a different origin)
app.use("*", async (c, next) => {
  const env = c.env as Env;
  if (!env.ALLOWED_ORIGIN) {
    return c.json({ error: "ALLOWED_ORIGIN not configured" }, 500);
  }
  return corsMiddleware(env.ALLOWED_ORIGIN)(c, next);
});

// Routes
app.post("/api/checkout", handleCheckout);
app.post("/api/webhook", handleWebhook);
app.post("/api/demo-token", handleDemoToken);
app.post("/api/demo-request", handleDemoRequest);

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

// 404 fallback
app.all("*", (c) => c.json({ error: "Not found" }, 404));

export default app;
