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

// New route segment config format
export const runtime = 'nodejs'; // Specify Node.js runtime
export const dynamic = 'force-dynamic'; // Ensure dynamic behavior
export const fetchCache = 'force-no-store'; // Disable caching

// Disable body parsing (new format)
export const maxDuration = 30; // Maximum execution time in seconds
export const preferredRegion = 'auto'; // Deployment region

export async function POST(request: NextRequest) {
  try {
    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 }
      );
    }

    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 }
      );
    }

    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 footersDir = join(process.cwd(), 'public', 'footers');

    if (!existsSync(footersDir)) {
      await mkdir(footersDir, { recursive: true });
    }

    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(footersDir, filename);

    await writeFile(filepath, new Uint8Array(bytes));

    return NextResponse.json({
      success: true,
      filename,
      path: `/footers/${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 }
    );
  }
}