package handlers

import (
	"database/sql"
	"net/http"
	"strconv"

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

var db *sql.DB

func InitDB(database *sql.DB) {
	db = database
}

type Comment struct {
	ID        int    `json:"id"`
	Name      string `json:"name"`
	Content   string `json:"content"`
	CreatedAt string `json:"created_at"`
}

type Response struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// 获取评论
func GetCommentsHandler(c *gin.Context) {
	pageStr := c.DefaultQuery("page", "1")
	sizeStr := c.DefaultQuery("size", "10")
	page, _ := strconv.Atoi(pageStr)
	size, _ := strconv.Atoi(sizeStr)
	if page < 1 {
		page = 1
	}

	comments := make([]Comment, 0)
	var total int64

	// 统计总数
	err := db.QueryRow("SELECT COUNT(*) FROM comments").Scan(&total)
	if err != nil {
		c.JSON(http.StatusOK, Response{Code: 500, Msg: err.Error()})
		return
	}

	var rows *sql.Rows
	if size != -1 {
		offset := (page - 1) * size
		rows, err = db.Query("SELECT id, name, content, created_at FROM comments ORDER BY created_at ASC LIMIT $1 OFFSET $2", size, offset)
	} else {
		rows, err = db.Query("SELECT id, name, content, created_at FROM comments ORDER BY created_at ASC")
	}
	if err != nil {
		c.JSON(http.StatusOK, Response{Code: 500, Msg: err.Error()})
		return
	}
	defer rows.Close()

	for rows.Next() {
		var comment Comment
		if err := rows.Scan(&comment.ID, &comment.Name, &comment.Content, &comment.CreatedAt); err != nil {
			c.JSON(http.StatusOK, Response{Code: 500, Msg: err.Error()})
			return
		}
		comments = append(comments, comment)
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": gin.H{
			"total":    total,
			"comments": comments,
		},
	})
}

// 添加评论
func AddCommentHandler(c *gin.Context) {
	var newComment Comment
	if err := c.ShouldBindJSON(&newComment); err != nil {
		c.JSON(http.StatusOK, Response{Code: 400, Msg: "Invalid request"})
		return
	}

	// 插入数据库
	var id int
	err := db.QueryRow(
		"INSERT INTO comments (name, content, created_at) VALUES ($1, $2, $3) RETURNING id",
		newComment.Name, newComment.Content, newComment.CreatedAt,
	).Scan(&id)
	if err != nil {
		c.JSON(http.StatusOK, Response{Code: 500, Msg: err.Error()})
		return
	}

	newComment.ID = id
	c.JSON(http.StatusOK, Response{
		Code: 0,
		Msg:  "Comment added",
		Data: newComment,
	})
}

// 删除评论
func DeleteCommentHandler(c *gin.Context) {
	id, err := strconv.Atoi(c.Query("id"))
	if err != nil || id <= 0 {
		c.JSON(http.StatusOK, Response{Code: 400, Msg: "Invalid ID"})
		return
	}

	result, err := db.Exec("DELETE FROM comments WHERE id = $1", id)
	if err != nil {
		c.JSON(http.StatusOK, Response{Code: 500, Msg: err.Error()})
		return
	}

	rowsAffected, _ := result.RowsAffected()
	if rowsAffected == 0 {
		c.JSON(http.StatusOK, Response{Code: 404, Msg: "Comment not found"})
		return
	}

	c.JSON(http.StatusOK, Response{
		Code: 0,
		Msg:  "Comment deleted",
		Data: nil,
	})
}
