package handlers

import (
	"fmt"
	"net/http"

	"software-download-center/database"

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

// DefaultAdminUsername 默认管理员用户名
const DefaultAdminUsername = "admin"

// DefaultAdminPassword 默认管理员密码
const DefaultAdminPassword = "admin123456"

// CheckInstallStatus 检查安装状态
func CheckInstallStatus(c *gin.Context) {
	isInitialized := database.IsDBInitialized()
	
	c.JSON(http.StatusOK, gin.H{
		"initialized": isInitialized,
		"default_admin": gin.H{
			"username": DefaultAdminUsername,
			"password": DefaultAdminPassword,
		},
	})
}

// InstallDatabaseRequest 数据库安装请求
type InstallDatabaseRequest struct {
	Type        string `json:"type" binding:"required,oneof=sqlite mysql"`
	Host        string `json:"host"`
	Port        string `json:"port"`
	User        string `json:"user"`
	Password    string `json:"password"`
	Database    string `json:"database"`
	TablePrefix string `json:"table_prefix"`
	DSN         string `json:"dsn"` // SQLite 数据目录
}

// InstallDatabase 安装数据库
func InstallDatabase(c *gin.Context) {
	// 检查是否已初始化
	if database.IsDBInitialized() {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "数据库已初始化，请使用设置页面修改配置",
		})
		return
	}

	var req InstallDatabaseRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "请求参数错误: " + err.Error(),
		})
		return
	}

	// 验证必填字段
	if req.Type == "mysql" {
		if req.Host == "" || req.Port == "" || req.User == "" || req.Database == "" {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": "MySQL 配置不完整：需要 host, port, user, database",
			})
			return
		}
	} else if req.Type == "sqlite" {
		if req.DSN == "" {
			req.DSN = "data"
		}
	}

	// 构建数据库配置
	config := &database.DatabaseConfig{
		Type:        req.Type,
		Host:        req.Host,
		Port:        req.Port,
		User:        req.User,
		Password:    req.Password,
		Database:    req.Database,
		TablePrefix: req.TablePrefix,
		DSN:         req.DSN,
	}

	// 初始化数据库
	if err := database.InitDBWithConfig(config); err != nil {
		AddLog("ERROR", fmt.Sprintf("数据库安装失败: %s (IP: %s)", err.Error(), c.ClientIP()))
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "数据库连接失败: " + err.Error(),
		})
		return
	}

	AddLog("INFO", fmt.Sprintf("数据库安装成功: 类型=%s (IP: %s)", req.Type, c.ClientIP()))
	
	c.JSON(http.StatusOK, gin.H{
		"message": "数据库安装成功",
		"type":    req.Type,
	})
}

// VerifyDefaultAdmin 验证默认管理员登录
func VerifyDefaultAdmin(username, password string) bool {
	return username == DefaultAdminUsername && password == DefaultAdminPassword
}
