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

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

const handler = createCipayBuyerHandler({
  client,
  storefront: { locator: import.meta.env.CIPAY_STOREFRONT_LOCATOR },
  resolveCustomer: async ({ headers }) => {
    // Replace this with your verified Astro session lookup.
    const session = await readVerifiedSession(headers.get("cookie"));
    return session
      ? { subject: session.userId, customerId: session.cipayCustomerId }
      : null;
  },
});

// Astro supplies a Web Request, so the handler response can be returned directly.
export const ALL: APIRoute = ({ request }) =>
  allowCipayRequest(request) ? handler(request) : rateLimited();

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