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

// GET - Tüm slider item'ları getir
export async function GET() {
  try {
    const items = await prisma.sliderItem.findMany({
      orderBy: { id: 'asc' },
    });

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

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

      const item = await prisma.sliderItem.create({
        data: {
          title: data.title,
          description: data.description,
          buttonText: data.buttonText,
          buttonLink: data.buttonLink,
          active: data.active ?? true,
        },
      });

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

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

      const item = await prisma.sliderItem.update({
        where: { id: data.id },
        data: {
          title: data.title,
          description: data.description,
          buttonText: data.buttonText,
          buttonLink: data.buttonLink,
          active: data.active,
        },
      });

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

// DELETE - Slider item 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.sliderItem.delete({
        where: { id: parseInt(id) },
      });

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