import { NextRequest, NextResponse } from 'next/server' import { validateUploadSecret } from '@/lib/auth' import { getRemoteFolder } from '@/lib/github' import { classifyFileChanges } from '@/lib/diff-files' import { getModelFolderPath } from '@/lib/model-paths' import { ensurePreparedStagingAssets } from '@/lib/upload-staging' import { parseStagingRequestBody } from '@/lib/upload-request' import { getErrorMessage } from '@/lib/guards' import type { FileDiff } from '@/lib/types' export const runtime = 'nodejs' export const dynamic = 'force-dynamic' /** * POST /api/upload/check * Build the final Git payload, then compare it with the remote folder. */ export async function POST(req: NextRequest) { const authError = validateUploadSecret(req) if (authError) return authError let stagingId: string try { const body: unknown = await req.json() stagingId = parseStagingRequestBody(body).stagingId } catch (err) { const message = getErrorMessage(err) return NextResponse.json({ success: false, error: message }, { status: 400 }) } try { const { folderName, filesToPush } = await ensurePreparedStagingAssets(stagingId) const folderPath = getModelFolderPath(folderName) const { exists, files } = await getRemoteFolder(folderPath) if (exists) { const remoteFileMap = new Map(files.map((file) => [file.name.toLowerCase(), file.size])) const { fileChanges, deletedFileNames } = classifyFileChanges(filesToPush, remoteFileMap, folderPath) const diffs: FileDiff[] = [] for (const [name, status] of fileChanges.entries()) { if (status === 'new' || status === 'changed') { diffs.push({ name, status }) } } diffs.push(...deletedFileNames.map((name) => ({ name, status: 'deleted' as const }))) return NextResponse.json({ success: true, exists: true, path: folderPath, diffs, }) } return NextResponse.json({ success: true, exists: false }) } catch (err) { const message = getErrorMessage(err) return NextResponse.json({ success: false, error: message }, { status: 500 }) } }