package user

import (
    "context"

    "bindbox-game/internal/repository/mysql/model"
)

type InventoryWithProduct struct {
    *model.UserInventory
    ProductName string  `json:"product_name"`
    ProductImages string `json:"product_images"`
}

func (s *service) ListInventoryWithProduct(ctx context.Context, userID int64, page, pageSize int) (items []*InventoryWithProduct, total int64, err error) {
    q := s.readDB.UserInventory.WithContext(ctx).ReadDB().Where(s.readDB.UserInventory.UserID.Eq(userID))
    total, err = q.Count()
    if err != nil {
        return nil, 0, err
    }
    if page <= 0 {
        page = 1
    }
    if pageSize <= 0 {
        pageSize = 20
    }
    if pageSize > 100 {
        pageSize = 100
    }
    rows, err := q.Order(s.readDB.UserInventory.ID.Desc()).Offset((page-1)*pageSize).Limit(pageSize).Find()
    if err != nil {
        return nil, 0, err
    }
    pidMap := make(map[int64]struct{})
    for _, r := range rows {
        if r.ProductID > 0 {
            pidMap[r.ProductID] = struct{}{}
        }
    }
    products := map[int64]*model.Products{}
    if len(pidMap) > 0 {
        ids := make([]int64, 0, len(pidMap))
        for id := range pidMap {
            ids = append(ids, id)
        }
        pros, err := s.readDB.Products.WithContext(ctx).ReadDB().Where(s.readDB.Products.ID.In(ids...)).Find()
        if err != nil {
            return nil, 0, err
        }
        for _, p := range pros {
            products[p.ID] = p
        }
    }
    items = make([]*InventoryWithProduct, len(rows))
    for i, r := range rows {
        p := products[r.ProductID]
        name := ""
        images := ""
        if p != nil {
            name = p.Name
            images = p.ImagesJSON
        }
        items[i] = &InventoryWithProduct{UserInventory: r, ProductName: name, ProductImages: images}
    }
    return items, total, nil
}