import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';
import { getPostsDirectory } from '@/lib/postsDirectory';

const postsDirectory = getPostsDirectory();

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const slug = searchParams.get('slug');
  const folderPath = searchParams.get('path') || '';
  if (!slug) {
    return NextResponse.json({ error: 'Missing slug' }, { status: 400 });
  }
  const filePath = folderPath && folderPath.trim() !== ''
    ? path.join(postsDirectory, folderPath, `${slug}.md`)
    : path.join(postsDirectory, `${slug}.md`);
  if (!fs.existsSync(filePath)) {
    return NextResponse.json({ error: 'File does not exist' }, { status: 404 });
  }
  const content = fs.readFileSync(filePath, 'utf8');
  return new NextResponse(content, { status: 200 });
} 