"use client";

import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { getAccountInfo, getOrganizerProfile } from "@/features/profile/services/profileApi";
import { sessionFlagsUpdate, type AccountSessionFlags } from "@/features/auth/sessionFlags";
import { useAuthStore } from "@/store/authStore";

/**
 * BE-108 workaround — tells the publish menu whether an organization account is
 * a volunteer team.
 *
 * `lib/publishPermissions.ts` decides "team" from
 * `user.organizer_type_display`, which the sign-in payload
 * (`WebsiteLoginUserResource`) does not send, so every team was treated as a
 * full organization and offered paid courses, internships and events the
 * server then refused. `GET /organization-profile/` does carry it.
 *
 * Mounted once in the main layout, so it runs for every signed-in organization
 * on whatever page they land on — not only after they happen to open one of the
 * screens that already fetch the profile. It shares their cache key, so it adds
 * no request on those screens. Once BE-108 puts the field on the sign-in
 * payload, the store already holds it and this only re-confirms it.
 */
export default function OrganizerTypeSync() {
  const isOrganization = useAuthStore(
    (s) => Boolean(s.user?.auth_token) && s.user?.user_type === "organization"
  );
  const storedValueEn = useAuthStore(
    (s) => s.user?.organizer_type_display?.value_en ?? null
  );
  const updateUser = useAuthStore((s) => s.updateUser);

  const { data } = useQuery({
    queryKey: ["organizer-profile"],
    queryFn: getOrganizerProfile,
    enabled: isOrganization,
    staleTime: 5 * 60 * 1000,
  });

  const display = data?.data?.organizer_type_display;

  /* Same key and fetcher as the header's avatar query, so this adds no
     request: the trainer approval and the publishing pause are decided by an
     admin after sign-in, and the stored session must follow them. */
  const signedIn = useAuthStore((s) => Boolean(s.user?.auth_token));
  const { data: account } = useQuery({
    queryKey: ["account-info"],
    queryFn: getAccountInfo,
    enabled: signedIn,
  });
  const flags = account?.data as AccountSessionFlags | undefined;
  useEffect(() => {
    const update = sessionFlagsUpdate(useAuthStore.getState().user, flags);
    if (update) updateUser(update);
  }, [flags, updateUser]);

  useEffect(() => {
    if (!isOrganization || !display) return;
    if (display.value_en === storedValueEn) return;
    updateUser({
      organizer_type_display: {
        id: display.id ?? undefined,
        value_en: display.value_en ?? null,
        value_ar: display.value_ar ?? null,
      },
    });
  }, [isOrganization, display, storedValueEn, updateUser]);

  return null;
}
