import { NextResponse } from 'next/server'
import { db } from '@/lib/db'

// GET - Fetch all articles
export async function GET() {
  try {
    const articles = await db.article.findMany({
      where: { published: true },
      orderBy: { createdAt: 'desc' },
      take: 6,
    })
    return NextResponse.json({ articles })
  } catch (error) {
    console.error('Error fetching articles:', error)
    return NextResponse.json({ articles: [], error: 'Failed to fetch articles' }, { status: 500 })
  }
}

// POST - Create a new article
export async function POST(request: Request) {
  try {
    const body = await request.json()
    const { title, slug, excerpt, content, category, image } = body

    const article = await db.article.create({
      data: {
        title,
        slug,
        excerpt,
        content,
        category,
        image: image || '/article-1.png',
        published: true,
      },
    })

    return NextResponse.json({ article })
  } catch (error) {
    console.error('Error creating article:', error)
    return NextResponse.json({ error: 'Failed to create article' }, { status: 500 })
  }
}
