import { io } from "socket.io-client";
import { BASE_URL } from "./constant";
import { configStore } from "../store/store";
const sockets = {};
export function initSocket(namespaceOrOptions = '/chat', options = {}) {
    let namespace = '/chat';
    let socketOptions = options;
    if (typeof namespaceOrOptions === 'string') {
        namespace = namespaceOrOptions;
    }
    else {
        // Legacy support: initSocket(options) where options is object
        socketOptions = namespaceOrOptions;
        namespace = '/chat';
    }
    if (!sockets[namespace]) {
        const baseUrl = BASE_URL();
        const url = baseUrl + namespace;
        const finalOptions = {
            transports: ['websocket'],
            autoConnect: true,
            reconnection: true,
            reconnectionDelay: 1000,
            reconnectionDelayMax: 10000,
            reconnectionAttempts: 10,
            timeout: 20000,
            forceNew: true,
            auth: {
                accessToken: configStore.get('accessToken'),
            },
            ...socketOptions,
        };
        const socket = io(url, finalOptions);
        sockets[namespace] = socket;
        socket.on('connect', () => {
            if (socket) {
                console.log(`[socket][${namespace}] Connected:`, socket.id);
            }
            else {
                console.log(`[socket][${namespace}] Cannot connect`);
            }
            if (namespace === '/chat') {
                const shopId = configStore.get('shopId');
                if (shopId)
                    joinRoom(shopId, namespace);
            }
        });
        socket.on('disconnect', () => {
            console.log(`[socket][${namespace}] Disconnected`);
        });
    }
    return sockets[namespace];
}
export function getSocket(namespace = '/chat') {
    return sockets[namespace] || null;
}
export function disconnectSocket(namespace) {
    if (namespace) {
        if (sockets[namespace]) {
            sockets[namespace].removeAllListeners();
            sockets[namespace].disconnect();
            delete sockets[namespace];
        }
    }
    else {
        Object.keys(sockets).forEach(ns => {
            if (sockets[ns]) {
                sockets[ns].removeAllListeners();
                sockets[ns].disconnect();
            }
        });
        for (const key in sockets)
            delete sockets[key];
    }
}
export function joinRoom(room, namespace = '/chat') {
    const socket = sockets[namespace];
    if (socket) {
        socket.emit('subscribe', { room });
        console.log(`[socket][${namespace}] Joined room: ${room}`);
    }
    else {
        console.warn(`[socket][${namespace}] Cannot join room: socket not initialized`);
    }
}
export function leaveRoom(room, namespace = '/chat') {
    const socket = sockets[namespace];
    if (socket) {
        socket.emit('unsubscribe', { room });
        console.log(`[socket][${namespace}] Leaved room: ${room}`);
    }
    else {
        console.warn(`[socket][${namespace}] Cannot leaved room: socket not initialized`);
    }
}
export function emitTyping(room, adminData) {
    const socket = sockets['/chat'];
    if (socket) {
        socket.emit('typing', { room, adminData });
    }
}
export function emitStopTyping(room) {
    const socket = sockets['/chat'];
    if (socket) {
        socket.emit('stop_typing', { room });
    }
}
