import { NextRequest, NextResponse } from 'next/server'
import { readFileSync, existsSync } from 'fs'
import { join, isAbsolute } from 'path'
import { getProjectContent } from '@/lib/storage/blob'

// Configuration - match collections route
const STARTER_PATH = process.env.STARTER_PATH || 'devdoc-docs'

// Get the docs directory - respects STARTER_PATH for local development
function getDocsDir(): string {
  const projectSlug = process.env.BRAINFISH_PROJECT_SLUG
  if (projectSlug) {
    return join(process.cwd(), '.devdoc', projectSlug)
  }
  
  // Use STARTER_PATH (can be absolute or relative)
  if (isAbsolute(STARTER_PATH)) {
    return STARTER_PATH
  }
  return join(process.cwd(), STARTER_PATH)
}

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams
  const path = searchParams.get('path')
  
  if (!path) {
    return NextResponse.json({ error: 'Missing path parameter' }, { status: 400 })
  }
  
  // Security: Only allow .graphql, .gql files
  if (!path.endsWith('.graphql') && !path.endsWith('.gql')) {
    return NextResponse.json({ error: 'Invalid file type' }, { status: 400 })
  }
  
  // Security: Prevent path traversal
  if (path.includes('..')) {
    return NextResponse.json({ error: 'Invalid path' }, { status: 400 })
  }
  
  try {
    // Try blob storage first (for deployed projects)
    const projectSlug = process.env.BRAINFISH_PROJECT_SLUG
    if (projectSlug) {
      const projectContent = await getProjectContent(projectSlug)
      if (projectContent?.files) {
        const file = projectContent.files.find(f => f.path === path || f.path === `/${path}`)
        if (file?.content) {
          return new NextResponse(file.content, {
            headers: { 'Content-Type': 'text/plain' }
          })
        }
      }
    }
    
    // Try local filesystem
    const docsDir = getDocsDir()
    const fullPath = join(docsDir, path)
    
    if (!existsSync(fullPath)) {
      return NextResponse.json({ error: 'Schema file not found' }, { status: 404 })
    }
    
    const content = readFileSync(fullPath, 'utf-8')
    
    return new NextResponse(content, {
      headers: { 'Content-Type': 'text/plain' }
    })
  } catch (error) {
    console.error('[Schema API] Error:', error)
    return NextResponse.json({ error: 'Failed to read schema' }, { status: 500 })
  }
}
