import { beforeEach, describe, expect, it, vi } from "vitest";
import { render, waitFor } from "@testing-library/react";
import UnreadNotificationsInit from "@/components/UnreadNotificationsInit";

const authState = vi.hoisted(() => ({
  authInfo: { token: "session-token" } as { token: string } | null,
  _hydrated: true,
}));

vi.mock("@/lib/auth/store", () => ({
  useAuthStore: (selector: (state: typeof authState) => unknown) =>
    selector(authState),
}));

const { refreshUnreadNotificationCount } = vi.hoisted(() => ({
  refreshUnreadNotificationCount: vi.fn(),
}));

vi.mock("@/lib/notifications/count", () => ({
  refreshUnreadNotificationCount,
}));

describe("UnreadNotificationsInit", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    authState.authInfo = { token: "session-token" };
    authState._hydrated = true;
  });

  it("refreshes unread count on app load when the user is logged in", async () => {
    render(<UnreadNotificationsInit />);

    await waitFor(() => {
      expect(refreshUnreadNotificationCount).toHaveBeenCalledTimes(1);
    });
  });

  it("skips refresh when auth is not hydrated yet", async () => {
    authState._hydrated = false;

    render(<UnreadNotificationsInit />);

    await waitFor(() => {
      expect(refreshUnreadNotificationCount).not.toHaveBeenCalled();
    });
  });

  it("skips refresh when there is no session token", async () => {
    authState.authInfo = null;

    render(<UnreadNotificationsInit />);

    await waitFor(() => {
      expect(refreshUnreadNotificationCount).not.toHaveBeenCalled();
    });
  });
});
