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

interface RouteParams {
  params: Promise<{ slug: string }>
}

/**
 * GET /api/projects/[slug]/stats
 * Get project statistics
 * 
 * Headers:
 *   Authorization: Bearer <api_key>
 */
export async function GET(request: NextRequest, { params }: RouteParams) {
  try {
    const { slug } = await params
    
    // Validate API key
    const authHeader = request.headers.get('Authorization')
    const apiKey = authHeader?.replace('Bearer ', '')
    
    if (!apiKey) {
      return NextResponse.json(
        { error: 'API key required' },
        { status: 401 }
      )
    }
    
    // Validate the API key belongs to this project
    const validatedSlug = await validateApiKey(apiKey)
    
    if (validatedSlug !== slug) {
      return NextResponse.json(
        { error: 'API key does not match this project' },
        { status: 403 }
      )
    }
    
    // Get project details
    const content = await getProjectContent(slug)
    const keyData = await getProjectApiKey(slug)
    
    if (!content) {
      return NextResponse.json(
        { error: 'Project not found' },
        { status: 404 }
      )
    }
    
    // Calculate stats
    const totalSize = content.files.reduce((sum, f) => sum + f.content.length, 0)
    const mdxFiles = content.files.filter(f => f.path.endsWith('.mdx') || f.path.endsWith('.md'))
    const jsonFiles = content.files.filter(f => f.path.endsWith('.json'))
    const otherFiles = content.files.filter(f => !f.path.endsWith('.mdx') && !f.path.endsWith('.md') && !f.path.endsWith('.json'))
    
    // Calculate days since creation
    const createdDate = new Date(content.createdAt)
    const now = new Date()
    const daysSinceCreation = Math.floor((now.getTime() - createdDate.getTime()) / (1000 * 60 * 60 * 24))
    
    return NextResponse.json({
      slug,
      stats: {
        totalFiles: content.files.length,
        mdxPages: mdxFiles.length,
        configFiles: jsonFiles.length,
        otherFiles: otherFiles.length,
        totalSizeBytes: totalSize,
        totalSizeKB: Math.round(totalSize / 1024 * 10) / 10,
      },
      deployment: {
        createdAt: content.createdAt,
        updatedAt: content.updatedAt,
        lastDeployedAt: keyData?.lastUsedAt || content.updatedAt,
        daysSinceCreation,
      },
      // Placeholder for future analytics
      analytics: {
        pageViews: 'coming soon',
        uniqueVisitors: 'coming soon',
      },
    })
    
  } catch (error) {
    console.error('[Projects Stats API] Error:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}
