import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/lib/supabase";
import { EventAndTablo, EventInsert } from "@/types/events.types";
import { useUser } from "@/providers/UserProvider";

export const useEventsByTablo = (tabloId: string | null) => {
  return useQuery({
    queryKey: ["events", tabloId],
    queryFn: async () => {
      if (!tabloId) {
        const { data, error } = await supabase
          .from("events_and_tablos")
          .select("*")
          .order("start_date", { ascending: true })
          .order("start_time", { ascending: true });

        if (error) throw error;
        return data as EventAndTablo[];
      }
      const { data, error } = await supabase
        .from("events_and_tablos")
        .select("*")
        .eq("tablo_id", tabloId)
        .order("start_date", { ascending: true })
        .order("start_time", { ascending: true });

      if (error) throw error;
      return data as EventAndTablo[];
    },
  });
};

export const useCreateEvent = () => {
  const user = useUser();
  const queryClient = useQueryClient();

  const { mutate } = useMutation({
    mutationFn: async (event: Omit<EventInsert, "created_by">) => {
      const { data, error } = await supabase
        .from("events")
        .insert({
          ...event,
          created_by: user.id,
        })
        .select()
        .single();

      if (error) throw error;
      return data as Event;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["events"] });
    },
    onError: (err) => {
      console.error(err);
    },
  });
  return mutate;
};
