/*
 This file is part of GNU Taler
 (C) 2025 Taler Systems S.A.

 GNU Taler is free software; you can redistribute it and/or modify it under the
 terms of the GNU General Public License as published by the Free Software
 Foundation; either version 3, or (at your option) any later version.

 GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

import { Logger } from "@gnu-taler/taler-util";
import { createServer } from "net";

const logger = new Logger("tan-helper.ts");

export interface TestTanHelperService {
  stop: () => void;
  getLastCodeForAddress(addr: string): string;
}

/**
 * Tan helper
 */
export async function startTanHelper(opts: {
  socketFile?: string;
}): Promise<TestTanHelperService> {
  const lastCodeForAddr: Record<string, string> = {};

  const server = createServer((socket) => {
    socket.on("data", (data) => {
      try {
        const jsonData = JSON.parse(data.toString().trim());
        const args: string[] =  jsonData.args;
        const idx = args.findIndex(a => a === "--")
        if (idx === -1) throw Error("missing '--' mark")
        const addr = args[idx+1]
        const code = jsonData.stdin;
        lastCodeForAddr[addr] = code;
      } catch (error) {
        console.error("Error parsing JSON:", error);
      }
    });

    socket.on("end", () => {
      console.log("Client disconnected");
    });
  });

  await new Promise<void>((resolve, reject) => {
    server.listen(opts.socketFile ?? "/tmp/tan-helper.socket", () => resolve());
  });
  return {
    stop() {
      server.close();
    },
    getLastCodeForAddress(address: string): string {
      return lastCodeForAddr[address];
    },
  };
}
