import { useMutation } from "@tanstack/react-query";
import { toast } from "@xtablo/shared";
import { useAuthedApi } from "./auth";

export interface WebcalToken {
  token: string;
  metadata: {
    tablo_id: string;
  };
  created_at: string;
}

export interface WebcalResponse {
  webcal_url: string;
  http_url: string;
}

// Generate a new webcal token
export const useGenerateWebcalToken = () => {
  const api = useAuthedApi();

  const { mutate, isPending, data } = useMutation({
    mutationFn: async (tablo_id: string | null): Promise<WebcalResponse> => {
      const { data } = await api.post("/api/v1/tablos/webcal/generate-url", {
        tablo_id,
      });
      return data;
    },
    onSuccess: () => {
      toast.add(
        {
          title: "URL de synchronisation générée",
          description: "Vous pouvez maintenant ajouter ce calendrier à votre application",
          type: "success",
        },
        {
          timeout: 4000,
        }
      );
    },
    onError: (error) => {
      console.error("Error generating webcal token:", error);
      toast.add(
        {
          title: "Erreur",
          description: "Impossible de générer l'URL de synchronisation",
          type: "error",
        },
        {
          timeout: 4000,
        }
      );
    },
  });

  return { generateWebcalUrl: mutate, isPending, data };
};
