import { NextRequest, NextResponse } from 'next/server' import { prisma } from '@/lib/prisma' import { withCors } from '@/lib/middleware' // 获取指定主机的星标记录 async function handleGetStarredRecords(req: NextRequest) { try { const { searchParams } = req.nextUrl const pathSegments = req.nextUrl.pathname.split('/') const hostnameIndex = pathSegments.indexOf('hosts') + 1 const hostname = pathSegments[hostnameIndex] const page = parseInt(searchParams.get('page') || '1') const limit = parseInt(searchParams.get('limit') || '50') const skip = (page - 1) * limit if (!hostname) { return NextResponse.json({ error: '主机名不能为空' }, { status: 400 }) } // 构建查询条件 - 只获取该主机的星标记录 const whereClause: any = { isStarred: true, hostname: hostname } // 获取星标记录 const records = await prisma.record.findMany({ where: whereClause, include: { windows: true, screenshots: true, host: { select: { hostname: true, lastUpdate: true } } }, orderBy: { timestamp: 'desc' }, skip, take: limit }) // 获取总数 const total = await prisma.record.count({ where: whereClause }) const serializedRecords = records.map(record => ({ ...record, windows: record.windows.map(window => ({ ...window, memory: window.memory.toString() })) })) return NextResponse.json({ records: serializedRecords, total, page, limit, totalPages: Math.ceil(total / limit) }) } catch (error) { console.error('获取星标记录失败:', error) return NextResponse.json({ error: '获取星标记录失败' }, { status: 500 }) } } // 批量操作星标记录 async function handlePostStarredRecords(req: NextRequest) { try { const pathSegments = req.nextUrl.pathname.split('/') const hostnameIndex = pathSegments.indexOf('hosts') + 1 const hostname = pathSegments[hostnameIndex] if (!hostname) { return NextResponse.json({ error: '主机名不能为空' }, { status: 400 }) } const body = await req.json() const { action, recordIds } = body if (!action || !recordIds || !Array.isArray(recordIds)) { return NextResponse.json({ error: '请求参数不正确,需要 action 和 recordIds 数组' }, { status: 400 }) } if (!['star', 'unstar'].includes(action)) { return NextResponse.json({ error: '无效的操作类型,只支持 star 或 unstar' }, { status: 400 }) } const isStarred = action === 'star' // 批量更新记录的星标状态 const result = await prisma.record.updateMany({ where: { id: { in: recordIds }, hostname: hostname }, data: { isStarred: isStarred } }) return NextResponse.json({ success: true, updatedCount: result.count, action: action, recordIds: recordIds }) } catch (error) { console.error('批量操作星标记录失败:', error) return NextResponse.json({ error: '批量操作星标记录失败' }, { status: 500 }) } } export const GET = withCors(handleGetStarredRecords) export const POST = withCors(handlePostStarredRecords)