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

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

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

    await markAllNotificationsAsRead(shopId);

    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" },
    });
  }
};
