import { NextRequest, NextResponse } from 'next/server'
import { writeFile, mkdir } from 'fs/promises'
import { join } from 'path'

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    console.log('API: Received request with fileName:', body.fileName)
    
    const { fileName, data } = body
    
    const dataDir = join(process.cwd(), 'data')
    const filePath = join(dataDir, fileName)
    
    console.log('API: Writing to:', filePath)
    
    try {
      await mkdir(dataDir, { recursive: true })
      console.log('API: Data directory created/verified')
    } catch (error) {
      console.log('API: Data directory already exists')
    }
    
    await writeFile(filePath, JSON.stringify(data, null, 2), 'utf8')
    console.log('API: File written successfully')
    
    return NextResponse.json({ 
      success: true, 
      message: 'Mesh data cached successfully',
      fileName 
    })
  } catch (error) {
    console.error('API: Error caching mesh data:', error)
    return NextResponse.json(
      { 
        success: false, 
        error: `Failed to cache mesh data: ${error}` 
      },
      { status: 500 }
    )
  }
} 