import type { ActionFunctionArgs } from "react-router";
import { markNotificationAsRead } from "../services/notification.server";
import { authenticateAdminRequest } from "../services/admin-auth.server";

export const action = async ({ request, params }: ActionFunctionArgs) => {
  const notificationId = params.id;
  const url = new URL(request.url);
  let shopId = url.searchParams.get("shopId");

  if (!notificationId) {
    return new Response(JSON.stringify({ error: "Missing notification ID" }), {
      status: 400,
      headers: { "Content-Type": "application/json" },
    });
  }

  try {
    const contentType = request.headers.get("content-type") || "";
    if (contentType.includes("application/json")) {
      const body = await request.json().catch(() => ({}));
      if (body.shopId) shopId = body.shopId;
    }

    if (shopId === "global") {
      const auth = authenticateAdminRequest(request);
      if (!auth.isAuthenticated) {
        return new Response(JSON.stringify({ error: "Unauthorized admin request" }), {
          status: 401,
          headers: { "Content-Type": "application/json" },
        });
      }
    }

    if (!shopId) {
      return new Response(JSON.stringify({ error: "Unauthorized: Valid shopId or tenant context required" }), {
        status: 401,
        headers: { "Content-Type": "application/json" },
      });
    }

    const updated = await markNotificationAsRead(notificationId, shopId);

    return new Response(JSON.stringify({ success: true, notification: updated }), {
      status: 200,
      headers: { "Content-Type": "application/json" },
    });
  } catch (error: any) {
    return new Response(JSON.stringify({ success: false, error: error.message || "Failed to mark notification as read" }), {
      status: 500,
      headers: { "Content-Type": "application/json" },
    });
  }
};
