import { NextRequest, NextResponse } from 'next/server' import connectDB from '@/lib/mongodb' import TopicModel, { transformToTopics } from '@/models/topic' export async function GET( request: NextRequest, { params }: { params: Promise<{ slug: string }> } ) { try { await connectDB() const { slug } = await params const searchParams = request.nextUrl.searchParams const limit = parseInt(searchParams.get('limit') || '2') if (!slug) { return NextResponse.json( { success: false, error: { message: 'Topic slug is required', code: 'SLUG_REQUIRED', }, }, { status: 400 } ) } // First, get the current post to find its ID and tags const currentPost = await TopicModel.findOne({ slug, isDraft: false }).lean() if (!currentPost) { return NextResponse.json({ success: true, data: [], }) } // Find related posts by excluding the current post and sorting by publishedAt const relatedPosts = await TopicModel.find({ id: { $ne: currentPost.id }, isDraft: false, }) .sort({ publishedAt: -1 }) .limit(limit) .lean() // Transform to proper format const transformedPosts = transformToTopics(relatedPosts) return NextResponse.json({ success: true, data: transformedPosts, }) } catch (error) { console.error('Error fetching related posts:', error) return NextResponse.json( { success: false, error: { message: 'Failed to fetch related posts', code: 'SERVER_ERROR', }, }, { status: 500 } ) } }