import { NextResponse } from 'next/server'
import { readFileSync, existsSync } from 'fs'
import { join, isAbsolute } from 'path'

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

// Helper to resolve paths - supports both relative and absolute STARTER_PATH
function resolvePath(...paths: string[]): string {
  if (isAbsolute(STARTER_PATH)) {
    return join(STARTER_PATH, ...paths)
  }
  return join(process.cwd(), STARTER_PATH, ...paths)
}

interface RedirectConfig {
  source: string
  destination: string
}

interface DocsConfig {
  redirects?: RedirectConfig[]
}

/**
 * GET /api/redirects
 * Returns the redirect configuration from docs.json
 */
export async function GET() {
  try {
    const docsJsonPath = resolvePath('docs.json')
    
    if (!existsSync(docsJsonPath)) {
      return NextResponse.json({ redirects: [] })
    }
    
    const docsJsonContent = readFileSync(docsJsonPath, 'utf-8')
    const docsConfig: DocsConfig = JSON.parse(docsJsonContent)
    
    return NextResponse.json({
      redirects: docsConfig.redirects || []
    })
  } catch (error) {
    console.error('[Redirects API] Error:', error)
    return NextResponse.json({ redirects: [] })
  }
}
