package handler

import (
	"net/http"

	"x-agents/server/internal/model"
	"x-agents/server/internal/service"

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

type DatabaseHandler struct {
	service *service.DatabaseService
}

func NewDatabaseHandler(svc *service.DatabaseService) *DatabaseHandler {
	return &DatabaseHandler{service: svc}
}

// Check 检查数据库连接
func (h *DatabaseHandler) Check(c *gin.Context) {
	var req model.CheckRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	result, err := h.service.Check(req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, result)
}

// Create 创建数据库信息
func (h *DatabaseHandler) Create(c *gin.Context) {
	var req model.CreateDatabaseRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	info, err := h.service.Create(req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, info)
}

// GetByID 获取详情
func (h *DatabaseHandler) GetByID(c *gin.Context) {
	id := c.Param("id")

	info, err := h.service.GetByID(id)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
		return
	}

	c.JSON(http.StatusOK, info)
}

// List 获取列表
func (h *DatabaseHandler) List(c *gin.Context) {
	list, err := h.service.List()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if list == nil {
		list = []model.DatabaseInfo{}
	}

	c.JSON(http.StatusOK, gin.H{"list": list})
}

// Update 更新
func (h *DatabaseHandler) Update(c *gin.Context) {
	id := c.Param("id")

	var req model.UpdateDatabaseRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	info, err := h.service.Update(id, req)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
		return
	}

	c.JSON(http.StatusOK, info)
}

// SaveGraph 保存图谱信息
func (h *DatabaseHandler) SaveGraph(c *gin.Context) {
	var req model.SaveGraphRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	result, err := h.service.SaveGraph(req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, result)
}

// Delete 删除
func (h *DatabaseHandler) Delete(c *gin.Context) {
	id := c.Param("id")

	err := h.service.Delete(id)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "deleted"})
}
