import { useQuery } from "@tanstack/react-query";

import { client } from "@/lib/rpc";
import { Workspace } from "../types";

interface useGetWorkspaceProps {
  workspaceId: string;
}

// Helper type for the API response
interface ApiWorkspace {
  id: string;
  name: string;
  imageUrl: string;
  inviteCode: string;
  userId: string;
  createdAt: string;
  updatedAt: string;
}

export const useGetWorkspace = ({ workspaceId }: useGetWorkspaceProps) => {
  const query = useQuery({
    queryKey: ["workspace", workspaceId],
    queryFn: async () => {
      const response = await client.api.workspaces[":workspaceId"].$get({
        param: { workspaceId },
      });

      if (!response.ok) {
        throw new Error("Failed to fetch workspace");
      }

      const { data } = await response.json();
      
      // Transform the date strings to Date objects
      const workspace = data as ApiWorkspace;
      return {
        ...workspace,
        createdAt: new Date(workspace.createdAt),
        updatedAt: new Date(workspace.updatedAt),
      } as Workspace;
    },
    enabled: !!workspaceId,
  });

  return query;
};
