// Centralized config for YourChat protocol mapping and WS endpoint
// Override via .env (VITE_* variables)

const env = import.meta.env || {};

export const CHAT_WS_URL = env.VITE_CHAT_WS_URL
  || (env.VITE_CHAT_WS_HOST || env.VITE_CHAT_WS_PORT
      ? `ws://${env.VITE_CHAT_WS_HOST || 'localhost'}:${env.VITE_CHAT_WS_PORT || '1235'}`
      : (typeof window !== 'undefined' && window.location.protocol === 'https:' ? 'wss://' : 'ws://') + window.location.host + '/socket.io/');

// Event/type keys
export const CHAT_EVENT_KEY = env.VITE_CHAT_EVENT_KEY || 'type';
export const CHAT_EVT_TOKEN = env.VITE_CHAT_EVT_TOKEN || 'token';
export const CHAT_EVT_AUTH = env.VITE_CHAT_EVT_AUTH || 'auth'; // optional, YourChat nutzt Token
export const CHAT_EVT_JOIN = env.VITE_CHAT_EVT_JOIN || 'join';
export const CHAT_EVT_MESSAGE = env.VITE_CHAT_EVT_MESSAGE || 'message';
export const CHAT_EVT_SYSTEM = env.VITE_CHAT_EVT_SYSTEM || 'system';

// Field names for payloads
export const CHAT_JOIN_ROOM_KEY = env.VITE_CHAT_JOIN_ROOM_KEY || 'newroom';
export const CHAT_JOIN_LEAVE_ROOM_KEY = env.VITE_CHAT_JOIN_LEAVE_ROOM_KEY || 'password'; // YourChat erwartet password Feld; leave optional nicht vorgesehen
export const CHAT_MESSAGE_ROOM_KEY = env.VITE_CHAT_MESSAGE_ROOM_KEY || null; // YourChat braucht kein roomId im message payload

export const CHAT_MSG_TEXT_KEY = env.VITE_CHAT_MSG_TEXT_KEY || 'message';
export const CHAT_MSG_FROM_KEY = env.VITE_CHAT_MSG_FROM_KEY || 'userName';
export const CHAT_MSG_ID_KEY = env.VITE_CHAT_MSG_ID_KEY || 'id';
export const CHAT_TOKEN_KEY = env.VITE_CHAT_TOKEN_KEY || 'token';

// Auth payload mapping
export const CHAT_AUTH_PAYLOAD_KEY = env.VITE_CHAT_AUTH_PAYLOAD_KEY || 'data';
export const CHAT_AUTH_USER_ID_KEY = env.VITE_CHAT_AUTH_USER_ID_KEY || 'userId';
export const CHAT_AUTH_AUTHCODE_KEY = env.VITE_CHAT_AUTH_AUTHCODE_KEY || 'authCode';

export function buildAuthPayload(user) {
  const payload = {};
  payload[CHAT_EVENT_KEY] = CHAT_EVT_AUTH;
  const dataObj = {};
  if (user?.id != null) dataObj[CHAT_AUTH_USER_ID_KEY] = user.id;
  if (user?.authCode != null) dataObj[CHAT_AUTH_AUTHCODE_KEY] = user.authCode;
  payload[CHAT_AUTH_PAYLOAD_KEY] = dataObj;
  return payload;
}

export function buildJoinPayload(roomName, password = '') {
  const payload = {};
  payload[CHAT_EVENT_KEY] = CHAT_EVT_JOIN;
  if (roomName != null) payload[CHAT_JOIN_ROOM_KEY] = roomName;
  if (CHAT_JOIN_LEAVE_ROOM_KEY) payload[CHAT_JOIN_LEAVE_ROOM_KEY] = password;
  return payload;
}

export function buildMessagePayload(text) {
  const payload = {};
  payload[CHAT_EVENT_KEY] = CHAT_EVT_MESSAGE;
  if (CHAT_MESSAGE_ROOM_KEY && typeof CHAT_MESSAGE_ROOM_KEY === 'string') payload[CHAT_MESSAGE_ROOM_KEY] = null;
  payload[CHAT_MSG_TEXT_KEY] = text;
  return payload;
}

export function parseIncomingMessage(data) {
  // Try JSON, else return as system text
  let obj = data;
  if (typeof data === 'string') {
    try { obj = JSON.parse(data); } catch (_) { return { type: 'system', text: String(data) }; }
  }
  const type = obj[CHAT_EVENT_KEY] || obj.type;
  if (type === CHAT_EVT_TOKEN) {
    return { type: 'token', token: obj.message };
  }
  if (type === CHAT_EVT_MESSAGE || type === 'message') {
    return {
      type: 'message',
      id: obj[CHAT_MSG_ID_KEY] || Date.now(),
      from: obj[CHAT_MSG_FROM_KEY] || 'User',
      text: obj[CHAT_MSG_TEXT_KEY] || ''
    };
  }
  if (type === CHAT_EVT_SYSTEM || type === 'system') {
    return {
      type: 'system',
      id: obj[CHAT_MSG_ID_KEY] || Date.now(),
      text: obj[CHAT_MSG_TEXT_KEY] || ''
    };
  }
  // Fallback: unknown event -> show raw
  return { type: 'system', id: Date.now(), text: JSON.stringify(obj) };
}
