import {
  createCipayBuyerHandler,
  createCipayClient,
} from "@cipay/client-sdk/api";
import { Hono } from "hono";
import { allowCipayRequest, rateLimited } from "../shared/rate-limit.js";

const client = createCipayClient({
  apiKey: process.env.CIPAY_SANDBOX_API_KEY!,
  mode: "sandbox",
});

const handler = createCipayBuyerHandler({
  client,
  storefront: { locator: process.env.CIPAY_STOREFRONT_LOCATOR! },
  resolveCustomer: async (request) => {
    // Resolve ownership from the authenticated application session.
    const session = await readVerifiedSession(request);
    return session
      ? { subject: session.userId, customerId: session.cipayCustomerId }
      : null;
  },
});

const app = new Hono();

app.all("/api/cipay/*", (context) => {
  // Hono already exposes the standard Web Request expected by Cipay.
  if (!allowCipayRequest(context.req.raw)) return rateLimited();
  return handler(context.req.raw);
});

async function readVerifiedSession(request: Request) {
  // Application integration point: replace this stub with verified server auth.
  void request;
  return null as null | { userId: string; cipayCustomerId: string };
}

export default app;
