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

export async function POST(request: NextRequest) {
  try {
    const data = await request.formData();
    const file: File | null = data.get('file') as unknown as File;

    if (!file) {
      return NextResponse.json({ error: "No file received." }, { status: 400 });
    }

    // Use Docker volume mount path for uploads
    const uploadsDir = process.env.NODE_ENV === 'production' 
      ? join(process.cwd(), 'uploads')  // Docker: /app/uploads
      : join(process.cwd(), 'public', 'uploads'); // Dev: public/uploads
      
    if (!existsSync(uploadsDir)) {
      await mkdir(uploadsDir, { recursive: true });
    }

    // Generate unique filename
    const timestamp = Date.now();
    const originalName = file.name.replace(/[^a-zA-Z0-9.-]/g, '_');
    const filename = `${timestamp}_${originalName}`;
    
    const bytes = await file.arrayBuffer();
    const buffer = Buffer.from(bytes);

    // Save file to uploads directory
    const filepath = join(uploadsDir, filename);
    await writeFile(filepath, buffer);

    // Return the public URL - in production, files are served from /uploads
    const fileUrl = `/uploads/${filename}`;
    
    return NextResponse.json({ 
      message: "File uploaded successfully", 
      url: fileUrl,
      filename: file.name,
      size: file.size,
      type: file.type
    });
    
  } catch (error) {
    console.error("Error uploading file:", error);
    return NextResponse.json({ error: "Error uploading file" }, { status: 500 });
  }
} 