package handler

import (
	"errors"
	"github.com/gofiber/fiber/v2"
	"gorm.io/gorm"
	"strconv"

	"gitee.ltd/lxh/wechat-robot/internal/model"
)

// ListMessages 获取联系人的聊天记录
func ListMessages(c *fiber.Ctx) error {
	robotID, err := strconv.Atoi(c.Params("id"))
	if err != nil {
		return fiber.NewError(fiber.StatusBadRequest, "无效的机器人ID")
	}

	contactID, err := strconv.Atoi(c.Params("contactId"))
	if err != nil {
		return fiber.NewError(fiber.StatusBadRequest, "无效的联系人ID")
	}

	// 获取分页参数
	page, _ := strconv.Atoi(c.Query("page", "1"))
	limit := 20
	offset := (page - 1) * limit

	db := model.GetDB()

	var robot model.Robot
	if err = db.First(&robot, robotID).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return fiber.NewError(fiber.StatusNotFound, "机器人不存在")
		}
		return fiber.NewError(fiber.StatusInternalServerError, "查询机器人失败")
	}

	var contact model.Contact
	if err = db.First(&contact, contactID).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return fiber.NewError(fiber.StatusNotFound, "联系人不存在")
		}
		return fiber.NewError(fiber.StatusInternalServerError, "查询联系人失败")
	}

	// 获取消息
	var messages []model.Message
	if err = db.Where("robot_id = ? AND contact_id = ?", robotID, contactID).
		Order("send_time DESC").
		Offset(offset).Limit(limit).
		Find(&messages).Error; err != nil {
		return fiber.NewError(fiber.StatusInternalServerError, "获取消息失败")
	}

	// 获取总消息数
	var total int64
	db.Model(&model.Message{}).Where("robot_id = ? AND contact_id = ?", robotID, contactID).Count(&total)

	// 计算总页数
	totalPages := int(total) / limit
	if int(total)%limit > 0 {
		totalPages++
	}

	return c.Render("message/index", fiber.Map{
		"Title":      contact.Nickname + " 聊天记录",
		"Robot":      robot,
		"Contact":    contact,
		"Messages":   messages,
		"Page":       page,
		"TotalPages": totalPages,
		"HasNext":    page < totalPages,
		"HasPrev":    page > 1,
		"NextPage":   page + 1,
		"PrevPage":   page - 1,
	})
}
