package handler

import (
	"net/http"
	"time"
	"xboard-go/internal/database"
	"xboard-go/internal/model"

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

// AdminKnowledgeFetch handles fetching of knowledge base articles.
func AdminKnowledgeFetch(c *gin.Context) {
	id := c.Query("id")
	if id != "" {
		var knowledge model.Knowledge
		if err := database.DB.Where("id = ?", id).First(&knowledge).Error; err != nil {
			Fail(c, http.StatusNotFound, "Article not found")
			return
		}
		Success(c, knowledge)
		return
	}

	var data []model.Knowledge
	database.DB.Select("id", "title", "category", "show", "updated_at", "sort").
		Order("sort ASC, id DESC").
		Find(&data)
	Success(c, data)
}

// AdminKnowledgeSave creates or updates a knowledge base article.
func AdminKnowledgeSave(c *gin.Context) {
	var payload model.Knowledge
	if err := c.ShouldBindJSON(&payload); err != nil {
		Fail(c, http.StatusBadRequest, "invalid request body")
		return
	}

	payload.UpdatedAt = time.Now().Unix()
	if payload.ID > 0 {
		if err := database.DB.Model(&model.Knowledge{}).Where("id = ?", payload.ID).Updates(payload).Error; err != nil {
			Fail(c, http.StatusInternalServerError, "failed to update article")
			return
		}
	} else {
		payload.CreatedAt = time.Now().Unix()
		if err := database.DB.Create(&payload).Error; err != nil {
			Fail(c, http.StatusInternalServerError, "failed to create article")
			return
		}
	}

	Success(c, true)
}

// AdminKnowledgeDrop deletes a knowledge base article.
func AdminKnowledgeDrop(c *gin.Context) {
	var payload struct {
		ID int `json:"id"`
	}
	if err := c.ShouldBindJSON(&payload); err != nil || payload.ID <= 0 {
		Fail(c, http.StatusBadRequest, "article id is required")
		return
	}

	if err := database.DB.Where("id = ?", payload.ID).Delete(&model.Knowledge{}).Error; err != nil {
		Fail(c, http.StatusInternalServerError, "failed to delete article")
		return
	}
	Success(c, true)
}

// AdminKnowledgeSort updates the sort order of knowledge base articles.
func AdminKnowledgeSort(c *gin.Context) {
	var payload struct {
		IDs []int `json:"ids"`
	}
	if err := c.ShouldBindJSON(&payload); err != nil {
		Fail(c, http.StatusBadRequest, "invalid request body")
		return
	}

	tx := database.DB.Begin()
	for i, id := range payload.IDs {
		tx.Model(&model.Knowledge{}).Where("id = ?", id).Update("sort", i+1)
	}
	tx.Commit()

	Success(c, true)
}
