import TcpSocket from "react-native-tcp-socket";

const STX = "\x02";
const ETX = "\x03";

type TcpResponse = {
	success: boolean;
	message: string;
	data: string[];
};

/**
 * Sends a Zebra-style TCP message:
 * <STX>98@{scanned}<ETX>
 */
export async function sendTcpMessage(
	scanned: string,
	host: string,
	port: number,
	timeoutMs = 5000,
): Promise<TcpResponse> {
	return new Promise((resolve) => {
		const responses: string[] = [];

		const client = TcpSocket.createConnection({ host, port }, () => {
			const payload = `${STX}98@${scanned}${ETX}`;

			console.log("Sending TCP (raw):", payload);
			console.log("Sending TCP (visible):", `<stx>98@${scanned}<etx>`);

			client.write(payload);
		});

		const timeout = setTimeout(() => {
			client.destroy();

			resolve({
				success: false,
				message: "TCP timeout",
				data: responses,
			});
		}, timeoutMs);

		client.on("data", (data) => {
			const text = data.toString();
			console.log("TCP received:", text);

			responses.push(text);
		});

		client.on("error", (err) => {
			clearTimeout(timeout);
			client.destroy();

			resolve({
				success: false,
				message: err.message,
				data: responses,
			});
		});

		client.on("close", () => {
			clearTimeout(timeout);

			resolve({
				success: true,
				message: "TCP complete",
				data: responses,
			});
		});
	});
}
