package handler

import (
	"net/http"

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

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

type SubTableHandler struct {
	service *service.SubTableService
}

func NewSubTableHandler(svc *service.SubTableService) *SubTableHandler {
	return &SubTableHandler{service: svc}
}

// Create 创建子表信息
func (h *SubTableHandler) Create(c *gin.Context) {
	var req model.CreateSubTableRequest
	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 *SubTableHandler) 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)
}

// ListByDatabase 获取数据库下所有子表
func (h *SubTableHandler) ListByDatabase(c *gin.Context) {
	databaseID := c.Param("database_id")

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

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

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

// GetMappingFromFile 从文件获取映射
func (h *SubTableHandler) GetMappingFromFile(c *gin.Context) {
	databaseID := c.Param("database_id")

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

	if mapping == nil {
		c.JSON(http.StatusOK, gin.H{"mapping": nil, "message": "no mapping file found"})
		return
	}

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

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

	var req model.UpdateSubTableRequest
	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)
}

// Delete 删除
func (h *SubTableHandler) 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"})
}

// GetTablesDDL 获取数据库下所有表及DDL
func (h *SubTableHandler) GetTablesDDL(c *gin.Context) {
	databaseID := c.Param("database_id")

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

	if tables == nil {
		tables = []model.TableDDLInfo{}
	}

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