package admin

import (
    "net/http"
    "strconv"

    "bindbox-game/internal/pkg/core"
    "bindbox-game/internal/service/recycle"
)

type recycleListResponse struct {
    Page     int              `json:"page"`
    PageSize int              `json:"page_size"`
    Total    int64            `json:"total"`
    List     []map[string]any `json:"list"`
}

func (h *handler) ListRecycle() core.HandlerFunc {
    return func(ctx core.Context) {
        typ := ctx.RequestInputParams().Get("type")
        pageStr := ctx.RequestInputParams().Get("page")
        sizeStr := ctx.RequestInputParams().Get("page_size")
        page, _ := strconv.Atoi(pageStr)
        size, _ := strconv.Atoi(sizeStr)
        svc := recycle.NewRaw(h.readDB, h.writeDB, h.repo.GetDbR(), h.repo.GetDbW())
        list, total, err := svc.List(ctx.RequestContext(), typ, page, size)
        if err != nil {
            ctx.AbortWithError(core.Error(http.StatusBadRequest, 19001, err.Error()))
            return
        }
        if page <= 0 { page = 1 }
        if size <= 0 { size = 20 }
        ctx.Payload(recycleListResponse{Page: page, PageSize: size, Total: total, List: list})
    }
}

func (h *handler) RestoreRecycle() core.HandlerFunc {
    return func(ctx core.Context) {
        typ := ctx.RequestInputParams().Get("type")
        idStr := ctx.RequestInputParams().Get("id")
        id, _ := strconv.ParseInt(idStr, 10, 64)
        svc := recycle.NewRaw(h.readDB, h.writeDB, h.repo.GetDbR(), h.repo.GetDbW())
        if err := svc.Restore(ctx.RequestContext(), typ, id); err != nil {
            ctx.AbortWithError(core.Error(http.StatusBadRequest, 19002, err.Error()))
            return
        }
        ctx.Payload(map[string]string{"message": "ok"})
    }
}

func (h *handler) ForceDeleteRecycle() core.HandlerFunc {
    return func(ctx core.Context) {
        typ := ctx.RequestInputParams().Get("type")
        idStr := ctx.RequestInputParams().Get("id")
        id, _ := strconv.ParseInt(idStr, 10, 64)
        svc := recycle.NewRaw(h.readDB, h.writeDB, h.repo.GetDbR(), h.repo.GetDbW())
        if err := svc.ForceDelete(ctx.RequestContext(), typ, id); err != nil {
            ctx.AbortWithError(core.Error(http.StatusBadRequest, 19003, err.Error()))
            return
        }
        ctx.Payload(map[string]string{"message": "ok"})
    }
}