import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { isAdminAuthenticated } from "@/lib/auth";

export async function PUT(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const isAuth = await isAdminAuthenticated();
    if (!isAuth) {
      return NextResponse.json(
        { error: "Bu işlem için yetkiniz yok (Admin girişi gerekli)" },
        { status: 401 }
      );
    }

    const { id } = await params;
    const body = await request.json();

    const {
      type,
      date,
      timestamp,
      mood,
      moodLabel,
      title,
      content,
      marginNotes,
      tags,
      likes,
      highlightWords,
      authorNote,
      imageUrl,
      imageCaption,
      codeSnippet,
      codeLanguage,
      audioDuration,
      audioTitle,
      stampedText,
    } = body;

    const updatedPost = await prisma.post.update({
      where: { id },
      data: {
        type,
        date,
        timestamp,
        mood,
        moodLabel,
        title,
        content,
        marginNotes: marginNotes || [],
        tags: tags || [],
        likes: likes !== undefined ? likes : undefined,
        highlightWords: highlightWords || [],
        authorNote,
        imageUrl,
        imageCaption,
        codeSnippet,
        codeLanguage,
        audioDuration,
        audioTitle,
        stampedText,
      },
    });

    return NextResponse.json(updatedPost);
  } catch (error) {
    console.error("Error updating post:", error);
    return NextResponse.json(
      { error: "Not güncellenirken sunucu hatası oluştu" },
      { status: 500 }
    );
  }
}

export async function DELETE(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const isAuth = await isAdminAuthenticated();
    if (!isAuth) {
      return NextResponse.json(
        { error: "Bu işlem için yetkiniz yok (Admin girişi gerekli)" },
        { status: 401 }
      );
    }

    const { id } = await params;
    await prisma.post.delete({
      where: { id },
    });

    return NextResponse.json({ success: true, message: "Not silindi" });
  } catch (error) {
    console.error("Error deleting post:", error);
    return NextResponse.json(
      { error: "Not silinirken sunucu hatası oluştu" },
      { status: 500 }
    );
  }
}
