import {
  deleteAllSession,
  deleteSession,
  getMySessions,
  sessionParams,
} from "@/record-management/services/api/sessionService";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useErrorHandler } from "./useErrorHandler";
import { useTranslation } from "react-i18next";

// --- Session Types ---
interface Session {
  id: string;
  email: string;
  device: string;
  createdAt: string;
}

interface SessionsResponse {
  sessions: Session[];
  total: number;
}


export const useSessions = (params: sessionParams) => {
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);
  const queryClient = useQueryClient();

  // --- Fetch Sessions ---
 const { data, isLoading, isError } = useQuery<SessionsResponse>({
   queryKey: ["my-sessions", params],
   queryFn: async () => {
     const res = await getMySessions(params);
     const [sessions, total] = res.data;
     return { sessions, total };
   },
 });



  

  // --- Delete Single Session ---
  const deleteSessionMutation = useMutation({
    mutationFn: (id: string) => deleteSession(id),
    onSuccess: () => {
      toast.success("Session revoked successfully");
      queryClient.invalidateQueries({ queryKey: ["my-sessions"] });
    },
    onError: (error: any) => {
      handleError(error);
    },
  });

  // --- Delete All Selected Sessions ---
  const deleteAllSessionsMutation = useMutation({
    mutationFn: (payload: { sessionIds: string[] }) =>
      deleteAllSession(payload),
    onSuccess: () => {
      toast.success("Selected sessions revoked successfully");
      queryClient.invalidateQueries({ queryKey: ["my-sessions"] });
    },
    onError: (error: any) => {
      handleError(error);
    },
  });

  return {
    data,
    isLoading,
    isError,
    deleteSession:deleteSessionMutation.mutate,
    deleteAllSessions: deleteAllSessionsMutation.mutate,
  };
};
