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

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

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

export const useGetWorkspaces = () => {
  const query = useQuery({
    queryKey: ["workspaces"],
    queryFn: async () => {
      const response = await client.api.workspaces.$get();

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

      const { data } = await response.json();
      
      // Transform the date strings to Date objects
      return (data.documents as ApiWorkspace[]).map(workspace => ({
        ...workspace,
        createdAt: new Date(workspace.createdAt),
        updatedAt: new Date(workspace.updatedAt),
      }));
    },
  });

  return query;
};
