package main

import (
	"fmt"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

// 用户拥有多个订单
//type User struct {
//	ID     uint    `gorm:"primaryKey"`
//	Name   string  `gorm:"size:100"`
//	Orders []Order // 一对多关联
//}
//
//type Order struct {
//	ID      uint   `gorm:"primaryKey"`
//	UserID  uint   // 外键
//	Product string `gorm:"size:100"`
//	Amount  int
//}

func main() {
	db, _ := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	db.AutoMigrate(&User{}, &Order{})

	// 1. 创建用户和订单
	user := User{
		Name: "Alice",
		Orders: []Order{
			{Product: "Laptop", Amount: 1},
			{Product: "Mouse", Amount: 2},
			{Product: "Keyboard", Amount: 1},
		},
	}
	db.Create(&user)
	fmt.Println("User and orders created")

	// 2. 预加载查询
	var result User
	db.Preload("Orders").First(&result, user.ID)
	fmt.Printf("User: %s, Orders: %d\n", result.Name, len(result.Orders))
	for _, order := range result.Orders {
		fmt.Printf("  - %s (x%d)\n", order.Product, order.Amount)
	}

	// 3. 添加新订单
	newOrder := Order{UserID: user.ID, Product: "Monitor", Amount: 1}
	db.Create(&newOrder)
	fmt.Println("New order added")

	// 4. 查询用户的所有订单
	var orders []Order
	db.Where("user_id = ?", user.ID).Find(&orders)
	fmt.Printf("Total orders: %d\n", len(orders))

	// 5. 删除某个订单
	db.Delete(&Order{}, orders[0].ID)
	fmt.Println("First order deleted")
}
