import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';

import { resolveStateDir } from '../config/paths.js';
import type { TunnelRegistration } from './tunnel-types.js';

export function resolveFrpcConfigPath(tunnelId: string): string {
  const tmpDir = join(resolveStateDir(), 'tmp');
  mkdirSync(tmpDir, { recursive: true });
  return join(tmpDir, `frpc-${tunnelId}.toml`);
}

export function writeFrpcConfig(
  registration: TunnelRegistration,
  localPort: number,
  localHost = '127.0.0.1',
  mode: 'http' | 'https' = 'http',
): string {
  const configPath = resolveFrpcConfigPath(registration.tunnelId);
  const { frpc } = registration;
  const toml = `# Auto-generated by xopc — do not edit
serverAddr = "${frpc.serverAddr}"
serverPort = ${frpc.serverPort}
metadatas.token = "${frpc.authToken}"

loginFailExit = false
transport.heartbeatInterval = 10
transport.heartbeatTimeout = 30

[[proxies]]
name = "${frpc.proxyName}"
type = "${mode}"
localIP = "${localHost}"
localPort = ${localPort}
subdomain = "${registration.subdomain}"
`;
  writeFileSync(configPath, toml, 'utf8');
  return configPath;
}
