package network

import (
	"customServer/internal/state"
	"encoding/json"
	"fmt"
	"net/http"
)

func StartHTTPServer(addr string) error {
	mux := http.NewServeMux()

	mux.HandleFunc("/main/v2/oauth/token", handleToken)
	mux.HandleFunc("/main/v1/user/me", handleUserMe)
	mux.HandleFunc("/main/v1/user/me/link", handleLink)
	mux.HandleFunc("/main/v1/users", handleUserSearch)
	mux.HandleFunc("/main/v3/showcase/games/steam/es", handleShowcase)
	mux.HandleFunc("/main/v1/user/me/buddies", handleBuddies)
	mux.HandleFunc("/main/v1/user/me/lastopponents/GOTDBG", handleLastOpponents)

	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Printf("[HTTP] [UNKNOWN] Request to %s (%s) from %s - Full URI: %s\n", r.URL.Path, r.Method, r.RemoteAddr, r.RequestURI)
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusNotFound)
		w.Write([]byte(`{"error":true,"status":404,"message":"Not found"}`))
	})

	fmt.Printf("[HTTP] REST API: http://localhost%s\n", addr)
	return http.ListenAndServe(addr, mux)
}

func handleToken(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("[HTTP] Request to %s from %s\n", r.URL.Path, r.RemoteAddr)
	response := map[string]interface{}{
		"access_token":  "mock_access_token_12345",
		"token_type":    "bearer",
		"expires_in":    3600,
		"refresh_token": "mock_refresh_token_67890",
		"scope":         "public private boardgames onlinegames partners features",
	}
	w.Header().Set("Content-Type", "application/json")
	data, _ := json.Marshal(response)
	w.Write(data)
}

func handleUserMe(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("[HTTP] Request to %s from %s\n", r.URL.Path, r.RemoteAddr)

	response := map[string]interface{}{
		"error":  false,
		"status": 200,
		"data": map[string]interface{}{
			"user": map[string]interface{}{
				"user_id":          state.MockUserID,
				"login_name":       state.MockUserName,
				"email":            "player@customserver.local",
				"name":             state.MockUserName,
				"email_valid":      true,
				"validated":        true,
				"country":          "US",
				"language":         "en",
				"time_zone":        "UTC",
				"posted_msg_count": 42,
				"features":         []string{"online_play", "all_expansions", "community", "profile", "userpages"},
				"partners": []interface{}{
					map[string]interface{}{
						"partner_id":      12, // Steam
						"partner_user_id": "76561198084728812",
						"created_at":      "2026-01-01T00:00:00Z",
					},
				},
				"boardgames":  []interface{}{},
				"onlinegames": []interface{}{},
				"avatar":      "https://uploads.asmodee.net/builtin/avatar-neutral.jpg",
			},
		},
	}

	w.Header().Set("Content-Type", "application/json")
	data, _ := json.Marshal(response)
	w.Write(data)
}

func handleLink(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("[HTTP] Request to %s (%s) from %s\n", r.URL.Path, r.Method, r.RemoteAddr)
	response := map[string]interface{}{
		"error":  false,
		"status": 200,
		"data":   map[string]interface{}{},
	}
	w.Header().Set("Content-Type", "application/json")
	data, _ := json.Marshal(response)
	w.Write(data)
}

func handleUserSearch(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("[HTTP] Request to %s from %s\n", r.URL.Path, r.RemoteAddr)

	response := map[string]interface{}{
		"error":  false,
		"status": 200,
		"data": map[string]interface{}{
			"total":  1,
			"_links": map[string]interface{}{},
			"users": []interface{}{
				map[string]interface{}{
					"user_id":     state.MockUserID,
					"login_name":  state.MockUserName,
					"avatar":      "https://uploads.asmodee.net/builtin/avatar-neutral.jpg",
					"features":    []string{"online_play", "all_expansions"},
					"boardgames":  []interface{}{},
					"onlinegames": []interface{}{},
				},
			},
		},
	}

	w.Header().Set("Content-Type", "application/json")
	data, _ := json.Marshal(response)
	w.Write(data)
}

func handleShowcase(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("[HTTP] Request to %s (%s) from %s\n", r.URL.Path, r.Method, r.RemoteAddr)
	response := map[string]interface{}{
		"error":  false,
		"status": 200,
		"data":   []interface{}{},
	}
	w.Header().Set("Content-Type", "application/json")
	data, _ := json.Marshal(response)
	w.Write(data)
}

func handleBuddies(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("[HTTP] Request to %s from %s\n", r.URL.Path, r.RemoteAddr)
	response := map[string]interface{}{
		"error":  false,
		"status": 200,
		"data": map[string]interface{}{
			"total":   0,
			"buddies": []interface{}{},
			"_links":  map[string]interface{}{},
		},
	}
	w.Header().Set("Content-Type", "application/json")
	data, _ := json.Marshal(response)
	w.Write(data)
}

func handleLastOpponents(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("[HTTP] Request to %s from %s\n", r.URL.Path, r.RemoteAddr)
	response := map[string]interface{}{
		"data": map[string]interface{}{
			"opponents": []interface{}{},
		},
	}
	w.Header().Set("Content-Type", "application/json")
	data, _ := json.Marshal(response)
	w.Write(data)
}
