import { NextResponse } from "next/server";
import { apiHandler, ApiError } from "@/lib/api";
import { suggestAlternativeItems } from "@/lib/ai";
import { searchPois } from "@/lib/amap";
import { getAuthUserId } from "@/lib/auth";

export const POST = apiHandler(async (req) => {
  await getAuthUserId(req);
  const { activity, time, location } = await req.json();
  if (!activity) throw new ApiError("activity 不能为空", 400);

  const alts = await suggestAlternativeItems(activity, time ?? "");
  if (!alts) throw new ApiError("AI 推荐失败，请重试", 500);

  // Parse location "lng,lat"
  let anchorLat = 31.23, anchorLng = 121.47; // default Shanghai
  if (location) {
    const [lng, lat] = location.split(",").map(Number);
    if (!isNaN(lat) && !isNaN(lng)) { anchorLat = lat; anchorLng = lng; }
  }

  // Parallel POI search with per-item fallback
  const results = await Promise.all(
    alts.map(async (alt) => {
      try {
        const pois = await searchPois(alt.searchQuery, "place", anchorLat, anchorLng);
        const top = pois[0];
        if (top) {
          return {
            activity: alt.activity,
            poi: top.name,
            address: top.address,
            lat: top.lat,
            lng: top.lng,
            reason: alt.reason,
          };
        }
      } catch (e) { console.error("suggest-item: POI search failed, using fallback:", e); }
      return {
        activity: alt.activity,
        poi: alt.searchQuery,
        address: "",
        lat: 0,
        lng: 0,
        reason: alt.reason,
      };
    }),
  );

  return NextResponse.json({ suggestions: results });
});
