import { NextRequest, NextResponse } from 'next/server'
import { readFile } from 'fs/promises'
import { existsSync } from 'fs'
import path from 'path'

export const dynamic = 'force-dynamic'

const MUGSHOT_DIR = path.join(process.cwd(), 'public', 'mugshots')

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ characterId: string }> }
) {
  try {
    const { characterId } = await params
    
    // Clean character ID for filename
    const safeCharId = characterId.replace(/[^a-zA-Z0-9_-]/g, '_')
    const filename = `${safeCharId}.png`
    const filepath = path.join(MUGSHOT_DIR, filename)

    // Check if mugshot exists
    if (!existsSync(filepath)) {
      // Return default avatar placeholder
      return NextResponse.json({
        exists: false,
        url: '/images/default-avatar.png',
      })
    }

    // Return mugshot info
    return NextResponse.json({
      exists: true,
      url: `/mugshots/${filename}`,
      characterId,
    })
  } catch (error) {
    console.error('[Mugshot] Retrieval error:', error)
    return NextResponse.json(
      { error: 'Failed to get mugshot' },
      { status: 500 }
    )
  }
}
