package server

import (
	"encoding/json"
	"net/http"
	"time"

	"github.com/bartered-dev/bartered/backend/internal/auth"
)

type messageResponse struct {
	Message string `json:"message"`
}

func NewHandler(store auth.Store) http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /health", health)
	mux.HandleFunc("GET /api/hello", hello)
	if store != nil {
		authAPI := authHandler{store: store, now: time.Now}
		mux.HandleFunc("POST /api/auth/register", authAPI.register)
		mux.HandleFunc("POST /api/auth/login", authAPI.login)
		mux.HandleFunc("GET /api/auth/me", authAPI.me)
		mux.HandleFunc("POST /api/auth/logout", authAPI.logout)
	}

	return withCORS(mux)
}

func health(response http.ResponseWriter, _ *http.Request) {
	writeJSON(response, http.StatusOK, messageResponse{Message: "ok"})
}

func hello(response http.ResponseWriter, _ *http.Request) {
	writeJSON(response, http.StatusOK, messageResponse{Message: "Hello from Bartered API"})
}

func writeJSON(response http.ResponseWriter, status int, value any) {
	response.Header().Set("Content-Type", "application/json")
	response.WriteHeader(status)
	_ = json.NewEncoder(response).Encode(value)
}

func withCORS(next http.Handler) http.Handler {
	return http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
		origin := request.Header.Get("Origin")
		if origin == "http://localhost:3000" || origin == "http://127.0.0.1:3000" {
			response.Header().Set("Access-Control-Allow-Origin", origin)
			response.Header().Set("Access-Control-Allow-Credentials", "true")
		}
		response.Header().Set("Access-Control-Allow-Headers", "Content-Type")
		response.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
		response.Header().Set("Vary", "Origin")
		if request.Method == http.MethodOptions {
			response.WriteHeader(http.StatusNoContent)
			return
		}
		next.ServeHTTP(response, request)
	})
}
