package message

import (
	"fmt"
	"net/http"

	"mini-chat/internal/code"
	"mini-chat/internal/pkg/core"
	"mini-chat/internal/pkg/timeutil"
	"mini-chat/internal/pkg/validation"

	"gorm.io/gorm"
)

type appMessagePageListRequest struct {
	AppID    string `form:"app_id" binding:"required"`  // 小程序ID
	UserID   string `form:"user_id" binding:"required"` // 用户ID
	Page     int    `form:"page"`                       // 当前页码，默认为第一页
	PageSize int    `form:"page_size"`                  // 每页返回的数据量
}

type listMessageData struct {
	SendTime   string `json:"send_time"`   // 发送时间
	SenderID   string `json:"sender_id"`   // 发送人ID
	SenderName string `json:"sender_name"` // 发送人昵称
	ReceiverID string `json:"receiver_id"` // 接收人ID
	Content    string `json:"content"`     // 消息内容
	MsgType    int32  `json:"msg_type"`    // 消息类型(1:文本 2:图片)
}

type appMessagePageListResponse struct {
	Page     int               `json:"page"`      // 当前页码
	PageSize int               `json:"page_size"` // 每页返回的数据量
	Total    int64             `json:"total"`     // 符合查询条件的总记录数
	List     []listMessageData `json:"list"`
}

// AppMessagePageList 获取消息日志
// @Summary 获取消息日志
// @Description 获取消息日志
// @Tags 用户端
// @Accept json
// @Produce json
// @Param app_id query string true "小程序ID"
// @Param user_id query string true "用户ID"
// @Param page query int true "当前页码" default(1)
// @Param page_size query int true "每页返回的数据量，最多 100 条" default(20)
// @Success 200 {object} appMessagePageListResponse
// @Failure 400 {object} code.Failure
// @Router /api/app/messages [get]
func (h *handler) AppMessagePageList() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(appMessagePageListRequest)
		res := new(appMessagePageListResponse)
		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 {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ListMessageError,
				fmt.Sprintf("%s: 一次最多只能查询 100 条", code.Text(code.ListMessageError)),
			))
			return
		}

		query := h.readDB.AppMessageLog.WithContext(ctx.RequestContext()).
			Where(h.readDB.AppMessageLog.AppID.Eq(req.AppID)).
			Where(h.readDB.AppMessageLog.SenderID.Eq(req.UserID)).Or(h.readDB.AppMessageLog.ReceiverID.Eq(req.UserID))

		listQueryDB := query.Session(&gorm.Session{})
		countQueryDB := query.Session(&gorm.Session{})

		resultData, err := listQueryDB.
			Order(h.readDB.AppMessageLog.SendTime.Desc()).
			Limit(req.PageSize).
			Offset((req.Page - 1) * req.PageSize).
			Find()
		if err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ListMessageError,
				fmt.Sprintf("%s：%s", code.Text(code.ListMessageError), err.Error())),
			)
			return
		}

		count, err := countQueryDB.Count()
		if err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ListMessageError,
				fmt.Sprintf("%s：%s", code.Text(code.ListMessageError), err.Error())),
			)
			return
		}

		res.Page = req.Page
		res.PageSize = req.PageSize
		res.Total = count
		res.List = make([]listMessageData, len(resultData))

		for k, v := range resultData {
			res.List[k] = listMessageData{
				SendTime:   timeutil.FriendlyTime(v.SendTime),
				SenderID:   v.SenderID,
				SenderName: v.SenderName,
				ReceiverID: v.ReceiverID,
				Content:    v.Content,
				MsgType:    v.MsgType,
			}
		}

		ctx.Payload(res)
	}
}
