package handler

import (
	"kra/internal/service"
	"kra/internal/service/dto"
	"time"

	"github.com/gin-gonic/gin"
)

type Announcement struct{ service *service.AnnouncementService }

func NewAnnouncement(service *service.AnnouncementService) *Announcement {
	return &Announcement{service: service}
}

func announcementInput(req dto.AnnouncementRequest) service.AnnouncementInput {
	return service.AnnouncementInput{ID: req.ID, Title: req.Title, Content: req.Content, UserID: req.UserID, Attachments: req.Attachments}
}

func (h *Announcement) Create(c *gin.Context) {
	var req dto.AnnouncementRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		Fail(c, err.Error())
		return
	}
	if err := h.service.Create(c.Request.Context(), announcementInput(req)); err != nil {
		Fail(c, "创建失败")
		return
	}
	Write(c, CodeSuccess, gin.H{}, "创建成功")
}

func (h *Announcement) Delete(c *gin.Context) {
	if err := h.service.Delete(c.Request.Context(), c.Query("ID")); err != nil {
		Fail(c, "删除失败")
		return
	}
	Write(c, CodeSuccess, gin.H{}, "删除成功")
}

func (h *Announcement) DeleteByIDs(c *gin.Context) {
	if err := h.service.DeleteByIDs(c.Request.Context(), c.QueryArray("IDs[]")); err != nil {
		Fail(c, "批量删除失败")
		return
	}
	Write(c, CodeSuccess, gin.H{}, "批量删除成功")
}

func (h *Announcement) Update(c *gin.Context) {
	var req dto.AnnouncementRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		Fail(c, err.Error())
		return
	}
	if err := h.service.Update(c.Request.Context(), announcementInput(req)); err != nil {
		Fail(c, "更新失败")
		return
	}
	Write(c, CodeSuccess, gin.H{}, "更新成功")
}

func (h *Announcement) Find(c *gin.Context) {
	item, err := h.service.Find(c.Request.Context(), c.Query("ID"))
	if err != nil {
		Fail(c, "查询失败")
		return
	}
	OKWithData(c, item)
}

func (h *Announcement) List(c *gin.Context) {
	var req dto.AnnouncementSearchRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		Fail(c, err.Error())
		return
	}
	items, total, err := h.service.List(c.Request.Context(), req.Page, req.PageSize, req.StartCreatedAt, req.EndCreatedAt)
	if err != nil {
		Fail(c, "获取失败")
		return
	}
	Write(c, CodeSuccess, PageResult{List: items, Total: total, Page: req.Page, PageSize: req.PageSize}, "获取成功")
}

func (h *Announcement) DataSource(c *gin.Context) {
	users, err := h.service.UserOptions(c.Request.Context())
	if err != nil {
		Fail(c, "查询失败")
		return
	}
	OKWithData(c, gin.H{"userID": users})
}

func (h *Announcement) Public(c *gin.Context) {
	Write(c, CodeSuccess, gin.H{"info": "不需要鉴权的公告接口信息"}, "获取成功")
}

func parseTime(value string) (*time.Time, error) {
	if value == "" {
		return nil, nil
	}
	parsed, err := time.Parse(time.RFC3339, value)
	if err != nil {
		return nil, err
	}
	return &parsed, nil
}
