export interface CommandResult {
	stdout: string;
	stderr: string;
	exitCode: number;
}

export async function runCommand(cmd: string, args: string[], env?: Record<string, string>): Promise<CommandResult> {
	const proc = Bun.spawn([cmd, ...args], {
		stdout: "pipe",
		stderr: "pipe",
		env: env ? { ...process.env, ...env } : undefined,
	});

	const stdout = await new Response(proc.stdout).text();
	const stderr = await new Response(proc.stderr).text();
	const exitCode = await proc.exited;

	return { stdout, stderr, exitCode };
}

const mbsyncBin = process.env.MBSYNC_BIN ?? "mbsync";
const notmuchEnv = process.env.NOTMUCH_CONFIG
	? { NOTMUCH_CONFIG: process.env.NOTMUCH_CONFIG }
	: undefined;

export async function syncMail(channelName: string): Promise<CommandResult> {
	return runCommand(mbsyncBin, [channelName]);
}

export async function indexMail(): Promise<CommandResult> {
	return runCommand("notmuch", ["new"], notmuchEnv);
}

export async function syncAndIndex(channelName: string): Promise<CommandResult> {
	const syncResult = await syncMail(channelName);
	if (syncResult.exitCode !== 0) {
		return syncResult;
	}
	return indexMail();
}
