export interface ParsedNode {
  name: string;
  type: string;
  server: string;
  port: number;
  surgeLine: string;
}

export function parseSS(uri: string): ParsedNode {
  const url = new URL(uri);
  const name = decodeURIComponent(url.hash.slice(1));
  const server = url.hostname;
  const port = parseInt(url.port, 10);

  const decoded = Buffer.from(url.username, 'base64').toString();
  const firstColon = decoded.indexOf(':');
  const method = decoded.slice(0, firstColon);
  const password = decoded.slice(firstColon + 1);

  // SS 2022 has built-in encryption, Surge does not support SS over TLS
  const surgeLine = `${name} = ss, ${server}, ${port}, encrypt-method=${method}, password=${password}`;

  return { name, type: 'ss', server, port, surgeLine };
}
