import { getPayload } from 'payload' import config from '@payload-config' import { NextRequest, NextResponse } from 'next/server' /** * Admin Management API * Combined endpoint for data clearing, stats, and diagnostics */ /** * GET /api/admin?action=stats * Get Payload collection statistics */ async function getStats() { const payload = await getPayload({ config }) const [products, preorderProducts] = await Promise.all([ payload.find({ collection: 'products', limit: 0 }), payload.find({ collection: 'preorder-products', limit: 0 }), ]) return { products: products.totalDocs, preorderProducts: preorderProducts.totalDocs, total: products.totalDocs + preorderProducts.totalDocs, } } /** * DELETE /api/admin * Clear Payload data (preserves Users and Media) * Query params: ?collections=products,preorderProducts,announcements,articles */ async function clearData(searchParams: URLSearchParams) { const payload = await getPayload({ config }) const collectionsParam = searchParams.get('collections') const collections = collectionsParam ? collectionsParam.split(',') : ['products', 'preorder-products', 'announcements', 'articles'] const results: Record = {} const errors: string[] = [] for (const collection of collections) { // Protect critical collections if (['users', 'media'].includes(collection)) { errors.push(`Skipped protected collection: ${collection}`) continue } try { const deleted = await payload.delete({ collection: collection as any, where: {}, }) results[collection] = deleted.docs?.length || 0 console.log(`✅ Cleared ${results[collection]} documents from ${collection}`) } catch (error) { const errorMsg = `Failed to clear ${collection}: ${error instanceof Error ? error.message : 'Unknown error'}` console.error('❌', errorMsg) errors.push(errorMsg) } } return { success: true, message: 'Data cleared successfully', results, errors: errors.length > 0 ? errors : undefined, } } export async function GET(request: NextRequest) { try { const { searchParams } = new URL(request.url) const action = searchParams.get('action') if (action === 'stats') { const stats = await getStats() return NextResponse.json({ success: true, ...stats }) } return NextResponse.json({ success: false, error: 'Invalid action. Valid actions: stats', }, { status: 400 }) } catch (error) { console.error('[admin] GET error:', error) return NextResponse.json({ success: false, error: error instanceof Error ? error.message : 'Unknown error', }, { status: 500 }) } } export async function DELETE(request: NextRequest) { try { const { searchParams } = new URL(request.url) const result = await clearData(searchParams) return NextResponse.json(result) } catch (error) { console.error('[admin] DELETE error:', error) return NextResponse.json({ success: false, error: error instanceof Error ? error.message : 'Unknown error', }, { status: 500 }) } }