package l7

import (
	"bytes"
	"strconv"
	"strings"
)

func ParseHttp(payload []byte) (string, string) {
	method, rest, ok := bytes.Cut(payload, space)
	if !ok {
		return "", ""
	}
	if !isHttpMethod(string(method)) {
		return "", ""
	}
	uri, _, ok := bytes.Cut(rest, space)
	if !ok {
		uri = append(uri, []byte("...")...)
	}
	return string(method), string(uri)
}

func ParseHttpHost(payload []byte) (string, string, string, uint16) {
	method, rest, ok := bytes.Cut(payload, space)
	if !ok {
		return "", "", "", 0
	}
	if !isHttpMethod(string(method)) {
		return "", "", "", 0
	}

	uri, rest, ok := bytes.Cut(rest, space)
	if !ok {
		uri = append(uri, []byte("...")...)
	}

	hostStart := bytes.Index(rest, []byte("Host:")) + len("Host:")
	hostEnd := bytes.Index(rest[hostStart:], []byte("\r\n"))
	hostPort := string(bytes.TrimSpace(rest[hostStart : hostStart+hostEnd]))
	hostParts := strings.Split(hostPort, ":")
	host := hostParts[0]
	port := uint16(80) // Default port
	if len(hostParts) > 1 {
		port64, err := strconv.ParseUint(hostParts[1], 10, 16)
		if err == nil {
			port = uint16(port64)
		}
	}

	return string(method), string(uri), host, port
}
