import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useSession } from "@xtablo/shared";
import { Database } from "@xtablo/shared/types/database.types";
import { supabase } from "../lib/supabase";

type Devis = Database["public"]["Tables"]["devis"];

type DevisInsert = Devis["Insert"];
type DevisUpdate = Devis["Update"];

// Fetch all devis
export const useDevisList = () => {
  return useQuery({
    queryKey: ["devis"],
    queryFn: async () => {
      const { data, error } = await supabase.from("devis").select("*");
      if (error) throw error;
      return data;
    },
  });
};

// Fetch single devis
export const useDevis = (id: string) => {
  return useQuery({
    queryKey: ["devis", id],
    queryFn: async () => {
      const { data, error } = await supabase.from("devis").select("*").eq("id", id);
      if (error) throw error;
      return data[0];
    },
  });
};

// Create new devis
export const useCreateDevis = () => {
  const { session } = useSession();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (devis: Omit<DevisInsert, "user_id">) => {
      const { error } = await supabase.from("devis").insert({
        ...devis,
        user_id: session?.user.id ?? "",
      });
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["devis"] });
    },
  });
};

// Update devis
export const useUpdateDevis = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ id, ...devis }: DevisUpdate & { id: string }) => {
      const { error } = await supabase.from("devis").update(devis).eq("id", id);
      if (error) throw error;
    },
    onSuccess: (_, { id }) => {
      queryClient.invalidateQueries({ queryKey: ["devis"] });
      queryClient.invalidateQueries({ queryKey: ["devis", id] });
    },
  });
};

// Delete devis
export const useDeleteDevis = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase.from("devis").delete().eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["devis"] });
    },
  });
};
