package mloco

import (
	"crypto/tls"
	"fmt"
	"net"
	"time"
)

const bookingHost = "booking-loco.kakao.com"

type bookingResponse struct {
	Ticket bookingTicket `bson:"ticket"`
	Wifi   bookingWifi   `bson:"wifi"`
}

type bookingTicket struct {
	LSL []string `bson:"lsl"`
}

type bookingWifi struct {
	Ports []int `bson:"ports"`
}

func getConf(timeout time.Duration) (*bookingResponse, error) {
	conn, err := tls.DialWithDialer(
		&net.Dialer{Timeout: timeout},
		"tcp",
		bookingHost+":443",
		&tls.Config{},
	)
	if err != nil {
		return nil, fmt.Errorf("tls dial booking: %w", err)
	}
	defer conn.Close()
	_ = conn.SetDeadline(time.Now().Add(timeout))

	body := encodeBSONDocument(docMap{
		"os":     agent,
		"model":  "",
		"MCCMNC": "",
	})

	pkt := packet{
		header: packetHeader{
			ID:       1000,
			Method:   "GETCONF",
			bodyType: 0,
			bodyLen:  uint32(len(body)),
		},
		body: body,
	}

	if _, err := conn.Write(pkt.encode()); err != nil {
		return nil, fmt.Errorf("send GETCONF: %w", err)
	}

	resp, err := readPacket(conn)
	if err != nil {
		return nil, fmt.Errorf("read GETCONF response: %w", err)
	}
	if err := resp.header.validate(); err != nil {
		return nil, fmt.Errorf("GETCONF error: %w", err)
	}
	if len(resp.body) == 0 {
		return nil, fmt.Errorf("GETCONF empty body")
	}

	doc, err := decodeBSONDocument(resp.body)
	if err != nil {
		return nil, fmt.Errorf("decode GETCONF body: %w", err)
	}

	return parseBookingResponse(doc)
}

func parseBookingResponse(doc map[string]any) (*bookingResponse, error) {
	result := &bookingResponse{}

	if t, ok := doc["ticket"].(map[string]any); ok {
		if lsl, ok := t["lsl"].([]any); ok {
			for _, v := range lsl {
				if s, ok := v.(string); ok {
					result.Ticket.LSL = append(result.Ticket.LSL, s)
				}
			}
		}
	}

	if w, ok := doc["wifi"].(map[string]any); ok {
		if ports, ok := w["ports"].([]any); ok {
			for _, v := range ports {
				switch p := v.(type) {
				case int32:
					result.Wifi.Ports = append(result.Wifi.Ports, int(p))
				case int64:
					result.Wifi.Ports = append(result.Wifi.Ports, int(p))
				case float64:
					result.Wifi.Ports = append(result.Wifi.Ports, int(p))
				}
			}
		}
	}

	if len(result.Ticket.LSL) == 0 || len(result.Wifi.Ports) == 0 {
		return nil, fmt.Errorf("booking: no hosts or ports in response")
	}

	return result, nil
}
