package main

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

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
)

type User struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

func main() {
	r := chi.NewRouter()

	// Built-in middleware
	r.Use(middleware.RequestID)
	r.Use(middleware.RealIP)
	r.Use(middleware.Logger)
	r.Use(middleware.Recoverer)
	r.Use(middleware.Timeout(60 * time.Second))

	// Routes
	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Welcome to the API"))
	})

	// Route groups with URL parameters
	r.Route("/users", func(r chi.Router) {
		r.Get("/", listUsers)         // GET /users
		r.Post("/", createUser)       // POST /users

		r.Route("/{userID}", func(r chi.Router) {
			r.Get("/", getUser)       // GET /users/{userID}
			r.Put("/", updateUser)    // PUT /users/{userID}
			r.Delete("/", deleteUser) // DELETE /users/{userID}
		})
	})

	log.Println("Server starting on :3000")
	http.ListenAndServe(":3000", r)
}

func listUsers(w http.ResponseWriter, r *http.Request) {
	users := []User{
		{ID: "1", Name: "Alice"},
		{ID: "2", Name: "Bob"},
	}
	json.NewEncoder(w).Encode(users)
}

func createUser(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusCreated)
	w.Write([]byte(`{"message": "user created"}`))
}

func getUser(w http.ResponseWriter, r *http.Request) {
	userID := chi.URLParam(r, "userID")
	user := User{ID: userID, Name: "User " + userID}
	json.NewEncoder(w).Encode(user)
}

func updateUser(w http.ResponseWriter, r *http.Request) {
	userID := chi.URLParam(r, "userID")
	w.Write([]byte(`{"message": "user ` + userID + ` updated"}`))
}

func deleteUser(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusNoContent)
}
