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

// New Route Segment Config (replaces export const config)
export const runtime = 'nodejs'; // Required for file system operations
export const dynamic = 'force-dynamic'; // Ensure dynamic server-side behavior
export const maxDuration = 30; // Maximum execution time (seconds)

// Body parsing is automatically disabled when using runtime: 'nodejs'

export async function POST(request: NextRequest) {
  try {
    // Verify content type
    const contentType = request.headers.get('content-type');
    if (!contentType?.includes('multipart/form-data')) {
      return NextResponse.json(
        { error: 'Content-Type must be multipart/form-data' },
        { status: 415 }
      );
    }

    const formData = await request.formData();
    const file = formData.get('file') as File | null;

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

    // Validate file type
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/svg+xml'];
    if (!allowedTypes.includes(file.type)) {
      return NextResponse.json(
        {
          error: 'Invalid file type',
          allowedTypes,
          receivedType: file.type
        },
        { status: 400 }
      );
    }

    // Validate file size (max 5MB)
    const maxSize = 5 * 1024 * 1024;
    if (file.size > maxSize) {
      return NextResponse.json(
        {
          error: 'File too large',
          maxSize,
          receivedSize: file.size
        },
        { status: 400 }
      );
    }

    const bytes = await file.arrayBuffer();
    const headersDir = join(process.cwd(), 'public', 'headers');

    // Ensure directory exists
    if (!existsSync(headersDir)) {
      await mkdir(headersDir, { recursive: true });
    }

    // Generate safe filename
    const sanitizedName = file.name.replace(/[^a-zA-Z0-9_.-]/g, '_');
    const extension = sanitizedName.split('.').pop()?.toLowerCase() || 'bin';
    const filename = `header-${Date.now()}.${extension}`;
    const filepath = join(headersDir, filename);

    // Write file
    await writeFile(filepath, new Uint8Array(bytes));

    return NextResponse.json({
      success: true,
      filename,
      path: `/headers/${filename}`,
      size: file.size,
      type: file.type
    });

  } catch (error) {
    console.error('Upload error:', error);
    return NextResponse.json(
      {
        error: 'Internal server error',
        ...(process.env.NODE_ENV === 'development' && {
          details: error instanceof Error ? error.message : String(error)
        })
      },
      { status: 500 }
    );
  }
}