import { NextResponse } from 'next/server'; import fs from 'fs'; import path from 'path'; import { getDatasetsRoot } from '@/server/settings'; const sanitizeSegment = (value: string): string => { if (!value || typeof value !== 'string') { return ''; } return value .toLowerCase() .replace(/[^a-z0-9]+/g, '_') .replace(/^_+|_+$/g, ''); }; export async function POST(request: Request) { try { const body = await request.json(); const { currentName, newName } = body ?? {}; if (!currentName || typeof currentName !== 'string') { return NextResponse.json({ error: 'Current dataset name is required' }, { status: 400 }); } if (!newName || typeof newName !== 'string') { return NextResponse.json({ error: 'New dataset name is required' }, { status: 400 }); } const datasetsRoot = await getDatasetsRoot(); const sanitizedCurrent = sanitizeSegment(currentName); const currentPath = path.join(datasetsRoot, sanitizedCurrent); if (!fs.existsSync(currentPath)) { return NextResponse.json({ error: `Dataset '${currentName}' not found` }, { status: 404 }); } const sanitizedNew = sanitizeSegment(newName); if (!sanitizedNew) { return NextResponse.json({ error: 'New dataset name is invalid' }, { status: 400 }); } if (sanitizedCurrent === sanitizedNew) { return NextResponse.json({ success: true, name: sanitizedCurrent, path: currentPath }); } const newPath = path.join(datasetsRoot, sanitizedNew); if (fs.existsSync(newPath)) { return NextResponse.json({ error: `Dataset '${sanitizedNew}' already exists` }, { status: 409 }); } fs.renameSync(currentPath, newPath); return NextResponse.json({ success: true, name: sanitizedNew, path: newPath }); } catch (error: any) { console.error('Dataset rename error:', error); return NextResponse.json({ error: error?.message || 'Failed to rename dataset' }, { status: 500 }); } }