import { WgServer } from "@lib/typings";

type Peer = WgServer['peers'][0]

interface GenPeerConParams extends Peer, Pick<WgServer, 'dns'> {
  serverAddress?: string
  serverPublicKey: string
  port: number
}


export async function getServerIP(): Promise<string> {
  const resp = await fetch('/api/host')
  return resp.text()
}

export async function getPeerConf(params: GenPeerConParams): Promise<string> {
  const serverAddress = params.serverAddress || await getServerIP()
  const lines = [
    '# Autogenerated by WireGuard UI (WireAdmin)',
    '[Interface]',
    `PrivateKey = ${params.privateKey}`,
    `Address = ${params.allowedIps}/24`,
    `${params.dns ? `DNS = ${params.dns}` : 'OMIT'}`,
    '',
    '[Peer]',
    `PublicKey = ${params.serverPublicKey}`,
    `${params.preSharedKey ? `PresharedKey = ${params.preSharedKey}` : 'OMIT'}`,
    `AllowedIPs = 0.0.0.0/0, ::/0`,
    `PersistentKeepalive = ${params.persistentKeepalive}`,
    `Endpoint = ${serverAddress}:${params.port}`,
  ]
  return lines
     .filter((l) => l !== 'OMIT')
     .join('\n')
}