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

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

    return NextResponse.json(documents);
  } catch (error) {
    console.error('Documents fetch error:', error);
    return NextResponse.json(
      { error: 'Dökümanlar alınırken hata oluştu' },
      { status: 500 }
    );
  }
}

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

      const document = await prisma.document.create({
        data: {
          title: data.title,
          type: data.type,
          category: data.category,
          downloadUrl: data.fileUrl || data.downloadUrl,
          size: data.fileSize || data.size || '0 MB',
          description: data.description,
          date: new Date().toISOString().split('T')[0],
        },
      });

      return NextResponse.json(document, { status: 201 });
    } catch (error) {
      console.error('Document create error:', error);
      return NextResponse.json(
        { error: 'Döküman oluşturulurken hata oluştu' },
        { status: 500 }
      );
    }
  });
}

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

      const document = await prisma.document.update({
        where: { id: data.id },
        data: {
          title: data.title,
          type: data.type,
          category: data.category,
          downloadUrl: data.fileUrl || data.downloadUrl,
          size: data.fileSize || data.size,
          description: data.description,
        },
      });

      return NextResponse.json(document);
    } catch (error) {
      console.error('Document update error:', error);
      return NextResponse.json(
        { error: 'Döküman güncellenirken hata oluştu' },
        { status: 500 }
      );
    }
  });
}

// DELETE - Döküman 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');

      console.log('DELETE document - ID:', id);

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

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

      return NextResponse.json({ message: 'Döküman silindi' });
    } catch (error: unknown) {
      console.error('Document delete error:', error);
      
      // Prisma P2025: Record not found
      if (error && typeof error === 'object' && 'code' in error && error.code === 'P2025') {
        return NextResponse.json(
          { error: 'Döküman bulunamadı (zaten silinmiş olabilir)' },
          { status: 404 }
        );
      }
      
      return NextResponse.json(
        { error: 'Döküman silinirken hata oluştu' },
        { status: 500 }
      );
    }
  });
}

