import type { ActionFunctionArgs } from "react-router";
import { markNotificationAsRead } from "../services/notification.server";
import { authenticateMerchantOrAdmin } from "../services/admin-auth.server";
import { assertTenantScope } from "../lib/security/tenant-context";

export const action = async ({ request, params }: ActionFunctionArgs) => {
  const notificationId = params.id;

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

  const auth = await authenticateMerchantOrAdmin(request);
  if (!auth.isAuthenticated) {
    return new Response(JSON.stringify({ error: "Unauthorized: Merchant or Admin authentication required" }), {
      status: 401,
      headers: { "Content-Type": "application/json" },
    });
  }

  const url = new URL(request.url);
  let body: any = {};
  const contentType = request.headers.get("content-type") || "";
  if (contentType.includes("application/json")) {
    body = await request.json().catch(() => ({}));
  }

  const requestedShopId = url.searchParams.get("shopId") || body.shopId;
  let effectiveShopId: string;

  if (auth.isSaaSAdmin) {
    effectiveShopId = requestedShopId || "global";
  } else {
    effectiveShopId = auth.shopId!;
    if (requestedShopId && requestedShopId !== "global") {
      try {
        assertTenantScope(requestedShopId, effectiveShopId);
      } catch (e: any) {
        return new Response(JSON.stringify({ error: "Cross-tenant access violation blocked" }), {
          status: 403,
          headers: { "Content-Type": "application/json" },
        });
      }
    }
  }

  try {
    const updated = await markNotificationAsRead(notificationId, effectiveShopId);

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