package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

// 用户结构体
type User struct {
	ID    int    `json:"id"`
	Name  string `json:"name" binding:"required"`
	Email string `json:"email" binding:"required,email"`
}

// 内存存储（实战应使用数据库）
var users = []User{
	{ID: 1, Name: "Alice", Email: "alice@example.com"},
	{ID: 2, Name: "Bob", Email: "bob@example.com"},
}

var nextID = 3

// 获取所有用户
func listUsers(c *gin.Context) {
	c.JSON(http.StatusOK, users)
}

// 获取单个用户
func getUser(c *gin.Context) {
	id := c.Param("id")
	for _, user := range users {
		if user.ID == intParam(id) {
			c.JSON(http.StatusOK, user)
			return
		}
	}
	c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
}

// 创建用户
func createUser(c *gin.Context) {
	var user User
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	user.ID = nextID
	nextID++
	users = append(users, user)
	c.JSON(http.StatusCreated, user)
}

// 更新用户
func updateUser(c *gin.Context) {
	id := c.Param("id")
	var user User

	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	for i, u := range users {
		if u.ID == intParam(id) {
			user.ID = u.ID
			users[i] = user
			c.JSON(http.StatusOK, user)
			return
		}
	}
	c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
}

// 删除用户
func deleteUser(c *gin.Context) {
	id := c.Param("id")
	for i, user := range users {
		if user.ID == intParam(id) {
			users = append(users[:i], users[i+1:]...)
			c.JSON(http.StatusNoContent, nil)
			return
		}
	}
	c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
}

// 辅助函数
func intParam(s string) int {
	var i int
	fmt.Sscanf(s, "%d", &i)
	return i
}

func main() {
	gin.SetMode(gin.ReleaseMode)
	r := gin.Default()

	// API 分组
	api := r.Group("/api")
	{
		users := api.Group("/users")
		{
			users.GET("", listUsers)
			users.POST("", createUser)
			users.GET("/:id", getUser)
			users.PUT("/:id", updateUser)
			users.DELETE("/:id", deleteUser)
		}
	}

	r.Run(":9999")
}
