import { NextRequest, NextResponse } from 'next/server'
import { promises as fs } from 'fs'
import path from 'path'

export async function GET(
  request: NextRequest,
  { params }: { params: { photo: string } }
) {
  try {
    const photoName = params.photo
    const photoPath = path.join(process.cwd(), 'public', 'team', photoName)
    
    try {
      // Try to serve the actual photo
      const imageBuffer = await fs.readFile(photoPath)
      const ext = path.extname(photoName).toLowerCase()
      
      let contentType = 'image/jpeg'
      if (ext === '.png') contentType = 'image/png'
      if (ext === '.gif') contentType = 'image/gif'
      if (ext === '.webp') contentType = 'image/webp'
      
      return new NextResponse(imageBuffer, {
        headers: {
          'Content-Type': contentType,
          'Cache-Control': 'public, max-age=31536000'
        }
      })
    } catch (fileError) {
      // If photo doesn't exist, serve default team image
      const placeholderPath = path.join(process.cwd(), 'public', 'team.png')
      const placeholderBuffer = await fs.readFile(placeholderPath)
      
      return new NextResponse(placeholderBuffer, {
        headers: {
          'Content-Type': 'image/png',
          'Cache-Control': 'public, max-age=3600'
        }
      })
    }
  } catch (error) {
    console.error('Team photo serve error:', error)
    return NextResponse.json({ error: 'Photo not found' }, { status: 404 })
  }
}
