import type { Context } from "../../../../../../packages/core/src/index.ts";
import {
  httpTransport,
  retryingTransport,
  ServiceError,
  serviceClient,
} from "../../../../../../packages/rpc/src/index.ts";
import { catalogService } from "../../../../packages/shared/src/index.ts";

/** GET /api/product?sku=starter — reads product data from the admin app. */
export async function GET(ctx: Context): Promise<Response> {
  const sku = new URL(ctx.req.url).searchParams.get("sku")?.trim() || "starter";
  const catalog = serviceClient(catalogService, {
    app: "admin",
    as: ctx,
    transport: retryingTransport(httpTransport()),
  });
  try {
    return Response.json({ product: await catalog.getProduct({ sku }) });
  } catch (error) {
    if (error instanceof ServiceError && error.code === "RPC_DENIED") {
      return Response.json({ error: "Forbidden" }, { status: 403 });
    }
    return Response.json({ error: "Catalog temporarily unavailable" }, { status: 502 });
  }
}
