import { io } from "socket.io-client";
import { useAppStore } from "../store/useAppStore";
import { api } from "../api/client";

let socket: ReturnType<typeof io> | null = null;

export const connectSocket = () => {
  if (socket) {
    return socket;
  }
  const baseUrl = import.meta.env.VITE_API_BASE || undefined;
  socket = io(baseUrl, {
    withCredentials: true,
    autoConnect: false,
  });

  api
    .get("/api/auth/socket-token")
    .then((response) => {
      socket!.auth = { token: response.data.token };
      socket!.connect();
    })
    .catch(() => {
      socket!.connect();
    });

  socket.on("status:snapshot", (snapshot) => {
    useAppStore.getState().setSnapshot(snapshot);
  });

  socket.on("status:update", (snapshot) => {
    useAppStore.getState().updateStatus(snapshot);
  });

  socket.on("job:metrics", (job) => {
    const state = useAppStore.getState();
    const jobs = state.jobs.map((existing) =>
      existing.id === job.id ? job : existing
    );
    state.updateStatus({ jobs });
  });

  socket.on("job:log", (log) => {
    useAppStore.getState().addLog(log);
  });

  socket.on("qbit:health", (qbit) => {
    useAppStore.getState().updateStatus({ qbit });
  });

  socket.on("timer:log", (log) => {
    useAppStore.getState().addTimerLog(log);
  });

  socket.on("timer:summary", (summary) => {
    useAppStore.getState().setTimerSummary(summary);
  });

  socket.on("watchers:list", (watchers) => {
    useAppStore.getState().setWatchers(watchers);
  });

  socket.on("watcher:items", (items) => {
    useAppStore.getState().setWatcherItems(items);
  });

  socket.on("watcher:summary", (summary) => {
    useAppStore.getState().setWatcherSummary(summary);
  });

  return socket;
};

export const disconnectSocket = () => {
  if (socket) {
    socket.disconnect();
    socket = null;
  }
};
