package handler

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"x-agents/server/internal/service"
)

type UploadHandler struct {
	uploadService *service.UploadService
}

func NewUploadHandler(uploadService *service.UploadService) *UploadHandler {
	return &UploadHandler{uploadService: uploadService}
}

// Upload 上传文件
func (h *UploadHandler) Upload(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "No file uploaded"})
		return
	}

	// 检查文件大小（最大 100MB）
	if file.Size > 100*1024*1024 {
		c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "File too large (max 100MB)"})
		return
	}

	result, err := h.uploadService.Upload(file)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": err.Error()})
		return
	}

	if !result.Success {
		c.JSON(http.StatusInternalServerError, result)
		return
	}

	c.JSON(http.StatusOK, result)
}

// Delete 删除文件
func (h *UploadHandler) Delete(c *gin.Context) {
	filename := c.Param("filename")
	if filename == "" {
		c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "Filename is required"})
		return
	}

	if err := h.uploadService.DeleteFile(filename); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": err.Error()})
		return
	}

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