import { NextRequest, NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import { getDatabase } from "@/lib/database";
import log from "@/lib/logger";

/**
 * PUT /api/notifications/[id]
 * Mark a notification as read
 */
export async function PUT(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  try {
    const { userId } = await auth();

    if (!userId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id } = await params;
    const db = await getDatabase();

    // Verify the notification belongs to the user
    const notifications = await db.getNotificationsByUserId(userId);
    const notification = notifications.find((n) => n.id === id);

    if (!notification) {
      return NextResponse.json(
        { error: "Notification not found" },
        { status: 404 },
      );
    }

    const updatedNotification = await db.markNotificationAsRead(id);

    return NextResponse.json({
      success: true,
      data: updatedNotification,
      meta: {
        timestamp: new Date().toISOString(),
      },
    });
  } catch (error) {
    log.error("Failed to mark notification as read", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}

/**
 * DELETE /api/notifications/[id]
 * Delete a notification
 */
export async function DELETE(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  try {
    const { userId } = await auth();

    if (!userId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id } = await params;
    const db = await getDatabase();

    // Verify the notification belongs to the user
    const notifications = await db.getNotificationsByUserId(userId);
    const notification = notifications.find((n) => n.id === id);

    if (!notification) {
      return NextResponse.json(
        { error: "Notification not found" },
        { status: 404 },
      );
    }

    const deleted = await db.deleteNotification(id);

    if (!deleted) {
      return NextResponse.json(
        { error: "Failed to delete notification" },
        { status: 500 },
      );
    }

    return NextResponse.json({
      success: true,
      data: { id },
      meta: {
        timestamp: new Date().toISOString(),
      },
    });
  } catch (error) {
    log.error("Failed to delete notification", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}
