import { getPayload } from 'payload' import config from '@payload-config' import { NextResponse } from 'next/server' /** * 批量同步选中的产品到 Medusa * POST /api/batch-sync-medusa * Body: { ids: string[], collection: 'products' | 'preorder-products', forceUpdate: boolean } */ export async function POST(request: Request) { try { const body = await request.json() const { ids, collection, forceUpdate = false } = body if (!ids || !Array.isArray(ids) || ids.length === 0) { return NextResponse.json( { success: false, error: 'No product IDs provided', }, { status: 400 }, ) } if (!collection || !['products', 'preorder-products'].includes(collection)) { return NextResponse.json( { success: false, error: 'Invalid collection', }, { status: 400 }, ) } const payload = await getPayload({ config }) const results = { total: ids.length, success: 0, failed: 0, details: [] as any[], } // 逐个同步选中的产品 for (const id of ids) { try { // 获取产品信息 const product = await payload.findByID({ collection: collection as 'products' | 'preorder-products', id, }) if (!product || !product.medusaId) { results.failed++ results.details.push({ id, title: product?.title || 'Unknown', status: 'failed', error: 'No Medusa ID', }) continue } // 调用单个产品同步 API const syncResponse = await fetch( `${request.url.replace('/api/batch-sync-medusa', '/api/sync-medusa')}?medusaId=${product.medusaId}&forceUpdate=${forceUpdate}`, { method: 'GET', headers: request.headers, }, ) const syncResult = await syncResponse.json() if (syncResult.success) { results.success++ results.details.push({ id, medusaId: product.medusaId, title: product.title, status: 'success', action: syncResult.action, }) } else { results.failed++ results.details.push({ id, medusaId: product.medusaId, title: product.title, status: 'failed', error: syncResult.error || syncResult.message, }) } } catch (error) { results.failed++ results.details.push({ id, status: 'failed', error: error instanceof Error ? error.message : 'Unknown error', }) } } return NextResponse.json({ success: true, message: `批量同步完成: ${results.success} 成功, ${results.failed} 失败`, results, }) } catch (error) { console.error('Batch sync error:', error) return NextResponse.json( { success: false, error: error instanceof Error ? error.message : 'Unknown error', }, { status: 500 }, ) } }