package api

import (
	"licserver/internal/service"
	"licserver/internal/utils"
	"net/http"

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

type SiteHandler struct {
	siteService *service.SiteService
}

func NewSiteHandler(siteService *service.SiteService) *SiteHandler {
	return &SiteHandler{siteService: siteService}
}

func (h *SiteHandler) GetSettings(c *gin.Context) {
	settings := h.siteService.GetSettings()
	c.JSON(http.StatusOK, gin.H{
		"code":        0,
		"data":        settings,
		"title":       settings.Title,
		"description": settings.Description,
		"base_url":    settings.BaseURL,
		"icp":         settings.ICP,
		"copyright":   settings.Copyright,
		"logo":        settings.Logo,
		"favicon":     settings.Favicon,
	})
}

func (h *SiteHandler) UpdateSettings(c *gin.Context) {
	var settings utils.SiteConfig
	if err := c.ShouldBindJSON(&settings); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := h.siteService.ValidateSettings(settings); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := h.siteService.UpdateSettings(settings); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "站点设置更新成功",
		"data":    settings,
	})
}

func (h *SiteHandler) BackupSettings(c *gin.Context) {
	settings := h.siteService.GetSettings()
	c.Header("Content-Disposition", "attachment; filename=site_settings.json")
	c.JSON(http.StatusOK, settings)
}

func (h *SiteHandler) RestoreSettings(c *gin.Context) {
	var settings utils.SiteConfig
	if err := c.ShouldBindJSON(&settings); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := h.siteService.ValidateSettings(settings); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := h.siteService.UpdateSettings(settings); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "站点设置恢复成功",
		"data":    settings,
	})
}
