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

export const action = async ({ request }: ActionFunctionArgs) => {
  if (request.method !== "PATCH" && request.method !== "POST") {
    return new Response(JSON.stringify({ error: "Method Not Allowed" }), {
      status: 405,
      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(() => ({}));
  } else if (contentType.includes("form-data") || contentType.includes("urlencoded")) {
    const formData = await request.formData();
    body = Object.fromEntries(formData.entries());
  }

  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 {
    await markAllNotificationsAsRead(effectiveShopId);

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