import { NextRequest, NextResponse } from "next/server"; import { z } from "zod"; import { auth } from "@/app/(auth)/auth"; import { queryThirdPartyImageMaterials, ThirdPartyImageMaterialError, } from "@/lib/agents/third-party-image-material-service"; import type { AgentWorkflowMaterialQueryType, AgentWorkflowMaterialResourceType, } from "@/types/agent"; export const maxDuration = 180; const querySchema = z.object({ resourceType: z.enum(["white-background", "task-detail"]).default("white-background"), sku: z.string().trim().max(64).optional(), spu: z.string().trim().max(64).optional(), keyword: z.string().trim().max(64).optional(), queryType: z.enum(["sku", "spu"]).optional(), }); function jsonNoStore(body: Parameters[0], init?: ResponseInit) { return NextResponse.json(body, { ...init, headers: { "Cache-Control": "no-store, max-age=0", ...(init?.headers || {}), }, }); } function resolveQuery(params: z.infer) { const spu = String(params.spu || "").trim(); const sku = String(params.sku || "").trim(); const keyword = String(params.keyword || "").trim(); if (spu) { return { queryType: "spu" as AgentWorkflowMaterialQueryType, keyword: spu, }; } if (sku) { return { queryType: "sku" as AgentWorkflowMaterialQueryType, keyword: sku, }; } if (keyword) { return { queryType: (params.queryType || "sku") as AgentWorkflowMaterialQueryType, keyword, }; } return null; } export async function GET(request: NextRequest) { try { const session = await auth(); if (!session?.user?.id) { return jsonNoStore({ error: "未登录" }, { status: 401 }); } const parsed = querySchema.parse({ resourceType: request.nextUrl.searchParams.get("resourceType") || undefined, sku: request.nextUrl.searchParams.get("sku") || undefined, spu: request.nextUrl.searchParams.get("spu") || undefined, keyword: request.nextUrl.searchParams.get("keyword") || undefined, queryType: request.nextUrl.searchParams.get("queryType") || undefined, }); const resolvedQuery = resolveQuery(parsed); if (!resolvedQuery) { return jsonNoStore( { success: false, error: { code: "MISSING_PARAM", message: "sku 和 spu 二选一必填;也可以传 keyword + queryType", }, }, { status: 400 } ); } const result = await queryThirdPartyImageMaterials({ resourceType: parsed.resourceType as AgentWorkflowMaterialResourceType, ...resolvedQuery, }); return jsonNoStore(result); } catch (error) { if (error instanceof ThirdPartyImageMaterialError) { return jsonNoStore( { success: false, error: { code: error.code, message: error.message, }, }, { status: error.status } ); } if (error instanceof z.ZodError) { return jsonNoStore( { success: false, error: { code: "INVALID_QUERY", message: "第三方图片素材查询参数无效", details: error.errors, }, }, { status: 400 } ); } console.error("[Third Party Image Materials] Search failed:", error); return jsonNoStore( { success: false, error: { code: "SERVER_ERROR", message: "第三方图片素材查询失败,请稍后重试", }, }, { status: 500 } ); } }