import { NextRequest, NextResponse } from 'next/server'
import { isAuthError, requireWorkspaceReadAccess } from '@/lib/auth/session'
import { GLOBAL_WORKSPACE_ID, getProjectPath, getWorkspacePath } from '@/lib/workspace-fs'
import fs from 'fs'
import path from 'path'

const MIME_TYPES: Record<string, string> = {
  '.png': 'image/png',
  '.jpg': 'image/jpeg',
  '.jpeg': 'image/jpeg',
  '.gif': 'image/gif',
  '.webp': 'image/webp',
  '.svg': 'image/svg+xml',
  '.bmp': 'image/bmp',
  '.ico': 'image/x-icon',
  '.mp4': 'video/mp4',
  '.webm': 'video/webm',
  '.mp3': 'audio/mpeg',
  '.wav': 'audio/wav',
  '.pdf': 'application/pdf',
}

function getMimeType(filename: string): string {
  const ext = path.extname(filename).toLowerCase()
  return MIME_TYPES[ext] || 'application/octet-stream'
}

function validateProjectPath(projectRoot: string, filePath: string): string | null {
  if (!filePath || filePath.includes('..') || path.isAbsolute(filePath)) return null
  const full = path.resolve(projectRoot, filePath)
  if (!full.startsWith(path.resolve(projectRoot) + path.sep)) return null
  return full
}

// GET /api/workspaces/[id]/raw?path=src/assets/logo.png   (project file)
// GET /api/workspaces/[id]/raw?name=logo.png              (forge config file)
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  try { await requireWorkspaceReadAccess(id) } catch (err) { if (isAuthError(err)) return err; throw err }

  const filePath = req.nextUrl.searchParams.get('path')
  const forgeName = req.nextUrl.searchParams.get('name')

  let fullPath: string | null = null
  let filename = ''

  if (filePath) {
    // Project file
    if (id === GLOBAL_WORKSPACE_ID) {
      return NextResponse.json({ error: 'project files are not available for global workspace' }, { status: 400 })
    }
    const projectRoot = getProjectPath(id)
    fullPath = validateProjectPath(projectRoot, filePath)
    filename = filePath
  } else if (forgeName) {
    // Forge config file
    if (forgeName.includes('..')) {
      return NextResponse.json({ error: 'Invalid filename' }, { status: 400 })
    }
    fullPath = path.join(getWorkspacePath(id), forgeName)
    filename = forgeName
  } else {
    return NextResponse.json({ error: 'path or name query param required' }, { status: 400 })
  }

  if (!fullPath || !fs.existsSync(fullPath)) {
    return NextResponse.json({ error: 'File not found' }, { status: 404 })
  }

  try {
    const buffer = fs.readFileSync(fullPath)
    const mimeType = getMimeType(filename)

    return new NextResponse(buffer, {
      headers: {
        'Content-Type': mimeType,
        'Cache-Control': 'public, max-age=300',
      },
    })
  } catch {
    return NextResponse.json({ error: 'Read failed' }, { status: 500 })
  }
}
