package main

import (
	"encoding/hex"
	"fmt"
	"net"
	"regexp"
	"time"
)

// ExtractDeviceIDFromBatchRaw 从批量原始数据中提取设备ID（序列号形如 1513343-01 或 ABC123-01）
func ExtractDeviceIDFromBatchRaw(data string) string {
	m := regexp.MustCompile(`([A-Za-z0-9]+)-\d+`).FindStringSubmatch(data)
	if len(m) == 2 {
		return m[1]
	}
	return ""
}

// ForwardRawData 将原始数据转发到设备配置的 TCP 目标
func ForwardRawData(deviceID string, raw string) error {
	if deviceID == "" {
		return nil
	}
	dev, err := GetDevice(deviceID)
	if err != nil || dev == nil {
		return err
	}
	if !dev.ForwardEnable {
		return nil
	}
	if !dev.Host.Valid || dev.Host.String == "" || !dev.Port.Valid || dev.Port.Int64 <= 0 {
		return nil
	}

	address := fmt.Sprintf("%s:%d", dev.Host.String, dev.Port.Int64)
	conn, err := net.DialTimeout("tcp", address, 5*time.Second)
	if err != nil {
		return err
	}
	defer conn.Close()

	if dev.RegCodeHex.Valid && dev.RegCodeHex.String != "" {
		bytes, decErr := hex.DecodeString(dev.RegCodeHex.String)
		if decErr == nil {
			_, _ = conn.Write(bytes)
			time.Sleep(1 * time.Second)
		}
	}

	_, err = conn.Write([]byte(raw))
	return err
}
