import ngrok from '@ngrok/ngrok';

export class NgrokTunnel {
  private listener: Awaited<ReturnType<typeof ngrok.forward>> | null = null;

  async start(port: number, domain?: string): Promise<string> {
    const authtoken = process.env.NGROK_AUTHTOKEN;
    if (!authtoken) {
      throw new Error(
        'NGROK_AUTHTOKEN environment variable is required.\n' +
          'Get your token at https://dashboard.ngrok.com/get-started/your-authtoken'
      );
    }

    this.listener = await ngrok.forward({
      addr: port,
      authtoken,
      ...(domain ? { domain } : {}),
    });

    const url = this.listener.url();
    if (!url) {
      throw new Error('ngrok tunnel started but no URL was returned');
    }
    return url;
  }

  getUrl(): string | null {
    return this.listener?.url() ?? null;
  }

  async stop(): Promise<void> {
    if (this.listener) {
      await this.listener.close();
      this.listener = null;
    }
  }
}
