import { useQuery } from "@tanstack/react-query";
import type { AxiosInstance } from "axios";
import { queryClient } from "../lib/api";

type EventTypeConfig = {
  name: string;
  description: string;
  duration: number; // in minutes
  bufferTime?: number; // buffer time before/after in minutes
  maxBookingsPerDay?: number;
  requiresApproval: boolean;
  price?: number;
  location?: string;
  minAdvanceBooking?: {
    value: number;
    unit: "minutes" | "hours" | "days";
  };
};

export type TimeSlot = {
  date: string;
  time: string;
  available: boolean;
};

export function usePublicSlots(api: AxiosInstance, shortUserId: string, standardName: string) {
  return useQuery<{
    user: { name: string; avatar_url?: string };
    eventType: EventTypeConfig;
    slots: { [date: string]: TimeSlot[] };
    availableSlots: TimeSlot[];
  }>({
    queryKey: ["public-slots", shortUserId, standardName],
    queryFn: async () => {
      const res = await api.get(`/api/v1/public/slots/${shortUserId}/${standardName}`);
      if (res.status !== 200) {
        throw new Error("Failed to fetch public slots");
      }
      return res.data;
    },
    enabled: !!shortUserId && !!standardName,
  });
}

export const invalidatePublicSlots = () => {
  queryClient.invalidateQueries({ queryKey: ["public-slots"] });
};
