import { Server } from "socket.io";
import axios from "axios";
import { handleConnectionEvents } from "./events/connection.js";
import { addUser, removeUser } from "./state/connection.js";
import gameEvents from "./events/game.js";
import matchEvents from "./events/match.js";

export const server = {
  io: null,
};

const API_URL = "http://localhost:8000/api/v1";

export const serverStart = (port) => {
  server.io = new Server(port, {
    cors: {
      origin: "*",
    },
  });

  server.io.use(async (socket, next) => {
    let token = socket.handshake.auth.token;

    if (!token) {
      return next(new Error("Authentication error: No token provided"));
    }

    if (!token.startsWith("Bearer ")) {
      token = "Bearer " + token;
    }

    try {
      const response = await axios.get(`${API_URL}/users/me`, {
        headers: { 
            Authorization: token,
            Accept: "application/json" 
        },
      });

      const user = response.data.data || response.data;

      if (!user || !user.id) {
        return next(new Error("Authentication error: User data not found"));
      }

      socket.user = user;
      socket.token = token;
      socket.handshake.auth.token = token; 

      addUser(socket.id, user); 

      next();
    } catch (error) {
      if (error.response) {
        console.error(
          "❌ Erro Laravel:",
          error.response.status,
          error.response.data
        );
      } else {
        console.error("❌ Erro Rede:", error.message);
      }
      next(new Error("Authentication error: Invalid token"));
    }
  });

  server.io.on("connection", (socket) => {
    gameEvents(server.io, socket);

    matchEvents(server.io, socket);

    handleConnectionEvents(server.io, socket);

    socket.on("disconnect", () => {
      removeUser(socket.id);
    });
  });
};