import { NextRequest, NextResponse } from 'next/server'
import { 
  validateApiKey, 
  regenerateApiKey,
  projectExists 
} from '@/lib/storage/blob'

/**
 * POST /api/keys/regenerate
 * Regenerate API key for a project
 * 
 * Headers:
 *   Authorization: Bearer <current_api_key>
 * Body:
 *   { slug: string }
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { slug } = body
    
    if (!slug || typeof slug !== 'string') {
      return NextResponse.json(
        { error: 'Missing or invalid project slug' },
        { status: 400 }
      )
    }
    
    // Validate current API key
    const authHeader = request.headers.get('Authorization')
    const currentKey = authHeader?.replace('Bearer ', '')
    
    if (!currentKey) {
      return NextResponse.json(
        { error: 'API key required' },
        { status: 401 }
      )
    }
    
    // Check project exists
    const exists = await projectExists(slug)
    if (!exists) {
      return NextResponse.json(
        { error: 'Project not found' },
        { status: 404 }
      )
    }
    
    // Validate the provided key belongs to this project
    const validatedSlug = await validateApiKey(currentKey)
    if (validatedSlug !== slug) {
      return NextResponse.json(
        { error: 'Invalid API key for this project' },
        { status: 403 }
      )
    }
    
    // Regenerate the key
    const newKey = await regenerateApiKey(slug, currentKey)
    
    if (!newKey) {
      return NextResponse.json(
        { error: 'Failed to regenerate API key' },
        { status: 500 }
      )
    }
    
    return NextResponse.json({
      success: true,
      apiKey: newKey,
    })
    
  } catch (error) {
    console.error('[Keys API] Error:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}
