import { NextRequest, NextResponse } from 'next/server'
import * as fs from 'fs'
import * as path from 'path'

/**
 * API route for serving infrastructure data JSON files
 * 
 * GET /api/infrastructure/data/[filename]
 * 
 * Serves JSON files from docs/infrastructure/data/ with caching headers
 */

const DATA_DIR = path.join(process.cwd(), 'docs/infrastructure/data')

// Allowed file extensions
const ALLOWED_EXTENSIONS = ['.json']

// Security: Prevent directory traversal
function sanitizeFilename(filename: string): string {
  // Remove any path separators and only allow alphanumeric, hyphens, underscores, and dots
  const sanitized = filename.replace(/[^a-zA-Z0-9._-]/g, '')
  // Ensure it has a valid extension
  const ext = path.extname(sanitized)
  if (!ALLOWED_EXTENSIONS.includes(ext)) {
    throw new Error('Invalid file extension')
  }
  return sanitized
}

export async function GET(
  request: NextRequest,
  { params }: { params: { filename: string } }
) {
  try {
    // Sanitize filename to prevent directory traversal
    const filename = sanitizeFilename(params.filename)
    const filePath = path.join(DATA_DIR, filename)

    // Check if file exists
    if (!fs.existsSync(filePath)) {
      return NextResponse.json(
        { error: 'File not found' },
        { status: 404 }
      )
    }

    // Read file content
    const fileContent = fs.readFileSync(filePath, 'utf-8')
    
    // Parse JSON to validate it's valid JSON
    let data: unknown
    try {
      data = JSON.parse(fileContent)
    } catch (parseError) {
      return NextResponse.json(
        { error: 'Invalid JSON file' },
        { status: 500 }
      )
    }

    // Get file stats for caching
    const stats = fs.statSync(filePath)

    // Create response
    const response = NextResponse.json({
      data,
      metadata: {
        filename,
        lastModified: stats.mtime.toISOString(),
        size: stats.size,
      },
    })

    // Add caching headers
    const etag = `"${stats.mtime.getTime()}-${stats.size}"`
    response.headers.set('ETag', etag)
    response.headers.set('Last-Modified', stats.mtime.toUTCString())
    response.headers.set('Cache-Control', 'public, max-age=3600, stale-while-revalidate=86400')
    response.headers.set('Content-Type', 'application/json')

    // Check if client has cached version (304 Not Modified)
    const ifNoneMatch = request.headers.get('if-none-match')
    if (ifNoneMatch === etag) {
      return new NextResponse(null, { status: 304 })
    }

    const ifModifiedSince = request.headers.get('if-modified-since')
    if (ifModifiedSince) {
      const ifModifiedSinceDate = new Date(ifModifiedSince)
      if (stats.mtime <= ifModifiedSinceDate) {
        return new NextResponse(null, { status: 304 })
      }
    }

    return response
  } catch (error) {
    // Handle security errors
    if (error instanceof Error && error.message === 'Invalid file extension') {
      return NextResponse.json(
        { error: 'Invalid file type. Only JSON files are allowed.' },
        { status: 400 }
      )
    }

    // Log error for debugging (in production, use proper logging)
    console.error('Error serving infrastructure data:', error)

    return NextResponse.json(
      { error: 'Failed to load file' },
      { status: 500 }
    )
  }
}

