package handlers

import (
	"customServer/internal/protocol"
	"customServer/internal/state"
	"fmt"
	"net"
	"time"
)

func HandleAsyncAuthRequest(conn net.Conn, requestData []byte) ([]byte, int) {
	fmt.Println("[TCP] Handling AsyncAuthRequest")

	// Session Message
	sessionData := make([]byte, 0)
	// field 1 (Id), Varint (WireType 0)
	sessionData = append(sessionData, 0x08)
	sessionData = append(sessionData, protocol.EncodeVarint(uint64(time.Now().UnixNano()))...)

	// Player Message
	player := state.GetMockPlayerBytes()

	// AsyncConnectedRequest
	asyncConnected := make([]byte, 0)
	// field 1 (Session), message
	asyncConnected = append(asyncConnected, 0x0a)
	asyncConnected = append(asyncConnected, protocol.EncodeVarint(uint64(len(sessionData)))...)
	asyncConnected = append(asyncConnected, sessionData...)

	// field 2 (Player), message
	asyncConnected = append(asyncConnected, 0x12)
	asyncConnected = append(asyncConnected, protocol.EncodeVarint(uint64(len(player)))...)
	asyncConnected = append(asyncConnected, player...)

	return asyncConnected, 406
}

func HandlePingRequest(conn net.Conn, requestData []byte) ([]byte, int) {
	fmt.Println("[TCP] Handling PingRequest")
	// The client sends a PingRequest with a timestamp (field 1).
	// We should respond with a PingRequest (777) containing the same timestamp.

	// Extract timestamp if possible, otherwise just send back a default one
	// For simplicity, we just echo back what we got if it's small, or send a new one.
	return requestData, 777
}

func HandleAsyncDisconnectRequest(conn net.Conn, requestData []byte) ([]byte, int) {
	fmt.Println("[TCP] Handling AsyncDisconnectRequest")
	return []byte{}, 401
}

func HandleAskServerStatisticsRequest(conn net.Conn, requestData []byte) ([]byte, int) {
	fmt.Println("[TCP] Handling AskServerStatisticsRequest")
	// Return ServerStatisticsRequest (409)
	// Fields: 1:HostedGames, 2:Players, 3:ConnectedPlayers (all int32)
	stats := make([]byte, 0)

	// Field 1: HostedGames (Varint)
	stats = append(stats, 0x08)
	stats = append(stats, protocol.EncodeVarint(1)...)

	// Field 2: Players (Varint)
	stats = append(stats, 0x10)
	stats = append(stats, protocol.EncodeVarint(1)...)

	// Field 3: ConnectedPlayers (Varint)
	stats = append(stats, 0x18)
	stats = append(stats, protocol.EncodeVarint(1)...)

	return stats, 409
}
