import { spawn } from 'node:child_process';
import { open } from 'node:fs/promises';

export class BackendServer {

	constructor(port) {
		this.process = null
		this.port = port
		this.exited = null
	}

	async start() {
		if (this.process) throw new Error('Backend already running');

		(await open('test.sqlite', 'a')).close()

		this.process = spawn('target/debug/ramistat', [
			'--database-url=sqlite://test.sqlite',
			`--bind-url=http://127.0.0.1:${this.port}`,
			'--scrambler-key=0000000000000000000000000000000000000000000000000000000000000000',
			'serve',
		]);

		await new Promise((started, start_failed) => {
			this.exited = new Promise(async (resolve_exited) => {
				let stderr = '';
				for await (const chunk of this.process.stderr) {
					//console.log(chunk.toString())
					if (stderr !== null) {
						stderr += chunk.toString();
						if (stderr.includes('Listening on')) {
							console.log(`Backend running:  ${this.fallback}@${this.port}`);
							stderr = null;
							started()
						}
					}
				}
				if (stderr !== null) start_failed(new Error('Backend process exited before printing "Listening on"'))
				this.process.on('exit', (code) => {
					console.log(`Backend exited:  ${this.fallback}@${this.port}`)
					resolve_exited(code)
				})
			})
		})
	}

	async stop() {
		if (this.process) {
			this.process.kill();
			await this.exited;
			this.process = null;
		}
	}
}
