import type { LoaderFunctionArgs } from "react-router";
import { getUnreadCount } from "../services/notification.server";
import { authenticateAdminRequest } from "../services/admin-auth.server";
import prisma from "../db.server";

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const url = new URL(request.url);
  const shopDomain = url.searchParams.get("shop");
  let shopId = url.searchParams.get("shopId");

  if (!shopId && shopDomain) {
    const shop = await prisma.shop.findUnique({
      where: { shopifyDomain: shopDomain.toLowerCase().trim() },
      select: { id: true },
    });
    if (shop) shopId = shop.id;
  }

  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 count = await getUnreadCount(shopId);

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