"use client";

import type { ReactNode } from "react";
import { useEffect } from "react";
import { useRouter } from "next/navigation";

import { useWorkspaceStore } from "@/lib/stores/workspace-store";
import { api } from "@/lib/trpc";

/**
 * Resolves the URL workspace handle (slug or UUID) to a full workspace record
 * and seeds the global workspace store. Other client components read from the
 * store and pass `currentWorkspace.slug` as the `workspace` arg to tenant-scoped
 * tRPC procedures.
 */
export function WorkspaceSync({
  workspaceSlug,
  children,
}: {
  workspaceSlug: string;
  children: ReactNode;
}) {
  const router = useRouter();
  const setWorkspace = useWorkspaceStore((s) => s.setWorkspace);

  const { data, isError } = api.workspaces.resolve.useQuery({
    handle: workspaceSlug,
  });

  useEffect(() => {
    if (data) {
      setWorkspace({
        id: data.id,
        slug: data.slug,
        name: data.name,
      });
      // URL backcompat: if the user landed on /<UUID>/... but the workspace
      // has a slug, rewrite the URL to the slug form so future links/share
      // surfaces are slug-shaped.
      if (workspaceSlug !== data.slug && typeof window !== "undefined") {
        const next = window.location.pathname.replace(
          `/${workspaceSlug}`,
          `/${data.slug}`,
        );
        router.replace(next + window.location.search);
      }
    }
    return () => setWorkspace(null);
  }, [workspaceSlug, data, setWorkspace, router]);

  if (isError) {
    return (
      <div className="flex h-full items-center justify-center p-8 text-sm text-muted-foreground">
        Workspace not found.
      </div>
    );
  }

  return <>{children}</>;
}
