import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { withAuth } from '@/lib/auth';

// GET - Tüm haberleri getir
export async function GET() {
  try {
    const news = await prisma.news.findMany({
      orderBy: { createdAt: 'desc' },
    });

    return NextResponse.json(news);
  } catch (error) {
    console.error('News fetch error:', error);
    return NextResponse.json(
      { error: 'Haberler alınırken hata oluştu' },
      { status: 500 }
    );
  }
}

// POST - Yeni haber ekle (Auth gerekli)
export async function POST(request: NextRequest) {
  return withAuth(request, async () => {
    try {
      const data = await request.json();

      const news = await prisma.news.create({
        data: {
          title: data.title,
          summary: data.summary || data.content.substring(0, 150) + '...',
          content: data.content,
          category: data.category,
          image: data.image,
          author: data.author,
          tags: data.tags || '',
          date: new Date().toISOString().split('T')[0],
          featured: data.featured || false,
        },
      });

      return NextResponse.json(news, { status: 201 });
    } catch (error) {
      console.error('News create error:', error);
      return NextResponse.json(
        { error: 'Haber oluşturulurken hata oluştu' },
        { status: 500 }
      );
    }
  });
}

// PUT - Haber güncelle (Auth gerekli)
export async function PUT(request: NextRequest) {
  return withAuth(request, async () => {
    try {
      const data = await request.json();

      const news = await prisma.news.update({
        where: { id: data.id },
        data: {
          title: data.title,
          summary: data.summary,
          content: data.content,
          category: data.category,
          image: data.image,
          author: data.author,
          tags: data.tags,
        },
      });

      return NextResponse.json(news);
    } catch (error) {
      console.error('News update error:', error);
      return NextResponse.json(
        { error: 'Haber güncellenirken hata oluştu' },
        { status: 500 }
      );
    }
  });
}

// DELETE - Haber sil (Auth gerekli)
export async function DELETE(request: NextRequest) {
  return withAuth(request, async () => {
    try {
      const { searchParams } = new URL(request.url);
      const id = searchParams.get('id');

      if (!id) {
        return NextResponse.json({ error: 'ID gerekli' }, { status: 400 });
      }

      await prisma.news.delete({
        where: { id: parseInt(id) },
      });

      return NextResponse.json({ message: 'Haber silindi' });
    } catch (error) {
      console.error('News delete error:', error);
      return NextResponse.json(
        { error: 'Haber silinirken hata oluştu' },
        { status: 500 }
      );
    }
  });
}
