/**
 * Single Notification API
 *
 * DELETE - Delete a specific notification
 * PATCH  - Mark a specific notification as read
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { logger } from "@/lib/logger";
import { withCSRF } from "@/lib/csrf";
import { convexMutation } from "@/lib/convex-client";

const scopedLogger = logger.scope("NotificationDetailAPI");

/**
 * DELETE /api/dashboard/notifications/[id]
 *
 * Delete a specific notification.
 *
 * Returns:
 * - success: true if deleted
 */
export const DELETE = withCSRF(
  async (
    request: NextRequest,
    { params }: { params: Promise<{ id: string }> },
  ) => {
    try {
      const { id } = await params;

      // Authenticate user
      const user = await getAuthenticatedUser(request, auth);

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

      // Validate notification ID
      if (!id || typeof id !== "string" || id.trim().length === 0) {
        return NextResponse.json(
          { success: false, error: "Invalid notification ID" },
          { status: 400 },
        );
      }

      // --- Convex data-source routing (strangler fig) ---
      if (getDataSource("notifications") === "convex") {
        try {
          const { convexMutation } = await import("@/lib/convex-client");
          // convexMutation accepts Record<string,unknown>; Convex Id<"notifications"> is a branded string
          await convexMutation("notifications/mutations:deleteNotification", {
            id,
          });
          scopedLogger.info("Notification deleted via Convex", {
            userId: user.userId,
            notificationId: id,
          });
          return NextResponse.json({ success: true });
        } catch (error) {
          scopedLogger.error("Failed to delete notification", error);
          return NextResponse.json(
            { success: false, error: "Internal server error" },
            { status: 500 },
          );
        }
      }
    } catch (error) {
      scopedLogger.error("Failed to delete notification", error);
      return NextResponse.json(
        { success: false, error: "Internal server error" },
        { status: 500 },
      );
    }
  },
);

/**
 * PATCH /api/dashboard/notifications/[id]
 *
 * Mark a specific notification as read.
 *
 * Returns:
 * - success: true if updated
 * - notification: Updated notification object
 */
export const PATCH = withCSRF(
  async (
    request: NextRequest,
    { params }: { params: Promise<{ id: string }> },
  ) => {
    try {
      const { id } = await params;

      // Authenticate user
      const user = await getAuthenticatedUser(request, auth);

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

      // Validate notification ID
      if (!id || typeof id !== "string" || id.trim().length === 0) {
        return NextResponse.json(
          { success: false, error: "Invalid notification ID" },
          { status: 400 },
        );
      }

      // --- Convex data-source routing (strangler fig) ---
      if (getDataSource("notifications") === "convex") {
        try {
          const { convexMutation } = await import("@/lib/convex-client");
          // convexMutation accepts Record<string,unknown>; Convex Id<"notifications"> is a branded string
          await convexMutation("notifications/mutations:markRead", { id });
          scopedLogger.info("Notification marked as read via Convex", {
            userId: user.userId,
            notificationId: id,
          });
          return NextResponse.json({ success: true, notification: { id } });
        } catch (error) {
          scopedLogger.error("Failed to mark notification as read", error);
          return NextResponse.json(
            { success: false, error: "Internal server error" },
            { status: 500 },
          );
        }
      }
    } catch (error) {
      scopedLogger.error("Failed to mark notification as read", error);
      return NextResponse.json(
        { success: false, error: "Internal server error" },
        { status: 500 },
      );
    }
  },
);
