package app

import (
    "encoding/json"
    "bindbox-game/internal/pkg/core"
    "bindbox-game/internal/pkg/logger"
    "bindbox-game/internal/repository/mysql"
    "bindbox-game/internal/repository/mysql/dao"
    cfgsvc "bindbox-game/internal/service/sysconfig"
)

type noticeHandler struct {
    logger logger.CustomLogger
    readDB *dao.Query
    cfg    cfgsvc.Service
}

func NewNotice(l logger.CustomLogger, db mysql.Repo) *noticeHandler {
    return &noticeHandler{logger: l, readDB: dao.Use(db.GetDbR()), cfg: cfgsvc.New(l, db)}
}

type appNoticeItem struct {
    Content string `json:"content"`
}

type listAppNoticesResponse struct {
    List []appNoticeItem `json:"list"`
}

// ListNoticesForApp 获取公告列表
// @Summary 获取公告列表
// @Description 获取APP首页滚动公告
// @Tags APP端.基础
// @Accept json
// @Produce json
// @Success 200 {object} listAppNoticesResponse
// @Router /api/app/notices [get]
func (h *noticeHandler) ListNoticesForApp() core.HandlerFunc {
    return func(ctx core.Context) {
        rsp := new(listAppNoticesResponse)
        conf, err := h.cfg.GetByKey(ctx.RequestContext(), "app_notice")
        if err != nil {
            rsp.List = []appNoticeItem{}
            ctx.Payload(rsp)
            return
        }
        val := conf.ConfigValue
        var arr []string
        if err := json.Unmarshal([]byte(val), &arr); err == nil {
            items := make([]appNoticeItem, 0, len(arr))
            for _, s := range arr { items = append(items, appNoticeItem{Content: s}) }
            rsp.List = items
            ctx.Payload(rsp)
            return
        }
        if val == "" {
            rsp.List = []appNoticeItem{}
            ctx.Payload(rsp)
            return
        }
        rsp.List = []appNoticeItem{{Content: val}}
        ctx.Payload(rsp)
    }
}
