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

export const loader = async ({ request }: LoaderFunctionArgs) => {
  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);
  const requestedShopId = url.searchParams.get("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" },
        });
      }
    }
  }

  const count = await getUnreadCount(effectiveShopId);

  return new Response(JSON.stringify({ count }), {
    status: 200,
    headers: {
      "Content-Type": "application/json",
      "Cache-Control": "no-cache, no-store, must-revalidate",
    },
  });
};
