package app

import (
    "bindbox-game/internal/code"
    "bindbox-game/internal/pkg/core"
    "bindbox-game/internal/pkg/validation"
    "bindbox-game/internal/pkg/logger"
    "bindbox-game/internal/repository/mysql"
    "bindbox-game/internal/repository/mysql/dao"
    "net/http"
)

type storeHandler struct {
    logger logger.CustomLogger
    readDB *dao.Query
}

func NewStore(logger logger.CustomLogger, db mysql.Repo) *storeHandler {
    return &storeHandler{logger: logger, readDB: dao.Use(db.GetDbR())}
}

type listStoreItemsRequest struct {
    Kind     string `form:"kind"`
    Page     int    `form:"page"`
    PageSize int    `form:"page_size"`
}

type listStoreItem struct {
    ID            int64  `json:"id"`
    Kind          string `json:"kind"`
    Name          string `json:"name"`
    MainImage     string `json:"main_image"`
    Price         int64  `json:"price"`
    InStock       bool   `json:"in_stock"`
    Status        int32  `json:"status"`
    DiscountType  int32  `json:"discount_type"`
    DiscountValue int64  `json:"discount_value"`
    MinSpend      int64  `json:"min_spend"`
    Supported     bool   `json:"supported"`
}

type listStoreItemsResponse struct {
    Total int64             `json:"total"`
    Page  int               `json:"page"`
    PageSize int            `json:"page_size"`
    List  []listStoreItem   `json:"list"`
}

func (h *storeHandler) ListStoreItemsForApp() core.HandlerFunc {
    return func(ctx core.Context) {
        req := new(listStoreItemsRequest)
        if err := ctx.ShouldBindForm(req); err != nil {
            ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, validation.Error(err)))
            return
        }
        if req.Page <= 0 { req.Page = 1 }
        if req.PageSize <= 0 { req.PageSize = 20 }
        if req.PageSize > 100 { req.PageSize = 100 }
        var total int64
		var list []listStoreItem
		offset := (req.Page - 1) * req.PageSize
		limit := req.PageSize

		switch req.Kind {
		case "item_card":
			q := h.readDB.SystemItemCards.WithContext(ctx.RequestContext()).ReadDB().Where(h.readDB.SystemItemCards.Status.Eq(1))
			total, _ = q.Count()
			rows, _ := q.Order(h.readDB.SystemItemCards.ID.Desc()).Offset(offset).Limit(limit).Find()
			list = make([]listStoreItem, len(rows))
			for i, it := range rows {
				list[i] = listStoreItem{ID: it.ID, Kind: "item_card", Name: it.Name, Price: it.Price, Status: it.Status, Supported: true}
			}
		case "coupon":
			q := h.readDB.SystemCoupons.WithContext(ctx.RequestContext()).ReadDB().Where(h.readDB.SystemCoupons.Status.Eq(1))
			total, _ = q.Count()
			rows, _ := q.Order(h.readDB.SystemCoupons.ID.Desc()).Offset(offset).Limit(limit).Find()
			list = make([]listStoreItem, len(rows))
			for i, it := range rows {
				list[i] = listStoreItem{ID: it.ID, Kind: "coupon", Name: it.Name, DiscountType: it.DiscountType, DiscountValue: it.DiscountValue, MinSpend: it.MinSpend, Status: it.Status, Supported: it.DiscountType == 1}
			}
		default: // product
			q := h.readDB.Products.WithContext(ctx.RequestContext()).ReadDB().Where(h.readDB.Products.Status.Eq(1))
			total, _ = q.Count()
			rows, _ := q.Order(h.readDB.Products.ID.Desc()).Offset(offset).Limit(limit).Find()
			list = make([]listStoreItem, len(rows))
			for i, it := range rows {
				list[i] = listStoreItem{ID: it.ID, Kind: "product", Name: it.Name, MainImage: parseFirstImage(it.ImagesJSON), Price: it.Price, InStock: it.Stock > 0 && it.Status == 1, Status: it.Status, Supported: true}
			}
		}

		ctx.Payload(&listStoreItemsResponse{
			Total:    total,
			Page:     req.Page,
			PageSize: req.PageSize,
			List:     list,
		})
	}
}

