package handler

import (
	"database/sql"
	"fmt"
	"net/http"
	"regexp"
	"strings"
	"time"

	"git.yeij.top/AskaEth/Cyrene/gateway/internal/middleware"

	"github.com/gin-gonic/gin"
	_ "github.com/lib/pq"
	"golang.org/x/crypto/bcrypt"

	"git.yeij.top/AskaEth/Cyrene/gateway/internal/config"
	"git.yeij.top/AskaEth/Cyrene/gateway/internal/store"
)

// usernameRegex 用户名格式校验：仅允许字母、数字、下划线，长度 3-32
var usernameRegex = regexp.MustCompile(`^[a-zA-Z0-9_]{3,32}$`)

// AuthHandler 认证处理器
type AuthHandler struct {
	cfg *config.Config
	db  *sql.DB
}

// NewAuthHandler 创建认证处理器
func NewAuthHandler(cfg *config.Config, db *sql.DB) *AuthHandler {
	return &AuthHandler{cfg: cfg, db: db}
}

// Register 用户注册 (需要邮箱验证码、昵称必填)
func (h *AuthHandler) Register(c *gin.Context) {
	// 检查注册开关
	if !h.cfg.RegistrationEnabled {
		c.JSON(http.StatusForbidden, gin.H{"error": "当前不开放公开注册，请使用管理员账户登录"})
		return
	}

	var req struct {
		Username string `json:"username" binding:"required,min=2,max=32"`
		Password string `json:"password" binding:"required,min=6,max=64"`
		Email    string `json:"email" binding:"required,email"`
		Nickname string `json:"nickname" binding:"required,min=1,max=32"`
		// MVP阶段：验证码仅做格式校验，后续接入邮件服务
		VerifyCode string `json:"verify_code" binding:"required,len=6"`
	}

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

	// 用户名格式校验：仅允许字母、数字、下划线，长度 3-32
	if !usernameRegex.MatchString(req.Username) {
		c.JSON(http.StatusBadRequest, gin.H{"error": "用户名格式无效：仅允许字母、数字和下划线，长度 3-32 位"})
		return
	}

	// MVP阶段：验证码简单校验 (开发环境接受 "000000")
	if req.VerifyCode != "000000" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "验证码错误 (开发阶段请使用 000000)"})
		return
	}

	// 邮箱域名简单校验
	if !strings.Contains(req.Email, "@") || !strings.Contains(req.Email, ".") {
		c.JSON(http.StatusBadRequest, gin.H{"error": "邮箱格式无效"})
		return
	}

	// 检查用户名是否已存在
	if h.db != nil {
		existingUser, err := store.GetUserByUsername(h.db, req.Username)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "服务器内部错误"})
			return
		}
		if existingUser != nil {
			c.JSON(http.StatusConflict, gin.H{"error": "用户名已被注册"})
			return
		}

		// 密码哈希
		passwordHash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "服务器内部错误"})
			return
		}

		// 存入 users 表
		_, err = store.CreateUser(h.db, req.Username, req.Nickname, string(passwordHash), false)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "注册失败: " + err.Error()})
			return
		}
	}

	// 生成 userID
	userID := "user_" + req.Username

	// 生成JWT
	token, err := h.cfg.GenerateToken(userID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "生成令牌失败"})
		return
	}

	// 生成 refresh_token (长期有效)
	refreshToken, err := h.cfg.GenerateRefreshToken(userID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "生成刷新令牌失败"})
		return
	}

	c.JSON(http.StatusCreated, gin.H{
		"user_id":       userID,
		"token":         token,
		"refresh_token": refreshToken,
		"expires":       time.Now().Add(h.cfg.JWTExpiryHours).Unix(),
		"nickname":      req.Nickname,
	})
}

// Login 用户登录
// 管理员始终通过 .env 配置验证，不受数据库状态影响
// 普通用户通过数据库 bcrypt 密码哈希验证
func (h *AuthHandler) Login(c *gin.Context) {
	var req struct {
		Username string `json:"username" binding:"required"`
		Password string `json:"password" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
		return
	}

	if !usernameRegex.MatchString(req.Username) {
		c.JSON(http.StatusBadRequest, gin.H{"error": "用户名格式无效"})
		return
	}

	var userID string
	var nickname string

	// 管理员：始终通过 .env 配置验证，不依赖数据库
	if req.Username == h.cfg.AdminUsername && req.Password == h.cfg.AdminPassword {
		userID = "admin"
		nickname = h.cfg.AdminNickname
		if nickname == "" {
			nickname = "管理员"
		}
		// 数据库可用时从 DB 获取昵称（覆盖配置默认值）
		if h.db != nil {
			if u, err := store.GetUserByUsername(h.db, req.Username); err == nil && u != nil {
				nickname = u.Nickname
			}
		}
	} else {
		// 普通用户：数据库 bcrypt 验证
		authenticated, err := h.verifyUserPassword(req.Username, req.Password)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "服务器内部错误"})
			return
		}
		if !authenticated {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名或密码错误"})
			return
		}
		userID = "user_" + req.Username
		if h.db != nil {
			if u, err := store.GetUserByUsername(h.db, req.Username); err == nil && u != nil {
				nickname = u.Nickname
			}
		}
	}

	token, err := h.cfg.GenerateToken(userID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "生成令牌失败"})
		return
	}

	refreshToken, err := h.cfg.GenerateRefreshToken(userID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "生成刷新令牌失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"user_id":       userID,
		"nickname":      nickname,
		"token":         token,
		"refresh_token": refreshToken,
		"expires":       time.Now().Add(h.cfg.JWTExpiryHours).Unix(),
	})
}

// verifyUserPassword 验证用户的密码
// 从数据库查询用户的密码哈希并与输入密码比对
// 如果用户不存在，返回 (false, nil)；如果密码匹配，返回 (true, nil)
func (h *AuthHandler) verifyUserPassword(username, password string) (bool, error) {
	if h.db == nil {
		// 数据库不可用时无法验证普通用户
		return false, nil
	}

	user, err := store.GetUserByUsername(h.db, username)
	if err != nil {
		return false, fmt.Errorf("查询用户失败: %w", err)
	}
	if user == nil {
		// 用户不存在
		return false, nil
	}

	// 使用 bcrypt 验证密码哈希
	if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)); err != nil {
		return false, nil
	}
	return true, nil
}

// RefreshToken 刷新令牌
// 支持两种方式：
// 1. 在 Authorization header 中传入有效的 access_token (可以已过期但 refresh_token 有效)
// 2. 在请求体中传入 refresh_token
func (h *AuthHandler) RefreshToken(c *gin.Context) {
	var userID string

	// 优先从请求体获取 refresh_token
	var req struct {
		RefreshToken string `json:"refresh_token"`
	}
	if err := c.ShouldBindJSON(&req); err == nil && req.RefreshToken != "" {
		uid, err := h.cfg.ValidateRefreshToken(req.RefreshToken)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "刷新令牌无效或已过期"})
			return
		}
		userID = uid
	} else {
		// 回退：从 Authorization header 获取 access_token 并验证
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" || len(authHeader) < 8 {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "未提供认证令牌"})
			return
		}

		tokenString := authHeader[7:] // 去掉 "Bearer "
		uid, err := h.cfg.ValidateToken(tokenString)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "令牌无效或已过期"})
			return
		}
		userID = uid
	}

	newToken, err := h.cfg.GenerateToken(userID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "刷新令牌失败"})
		return
	}

	// 生成新的 refresh_token
	newRefreshToken, err := h.cfg.GenerateRefreshToken(userID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "生成刷新令牌失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"token":         newToken,
		"refresh_token": newRefreshToken,
		"expires":       time.Now().Add(h.cfg.JWTExpiryHours).Unix(),
	})
}

// GetProfile 查询当前登录用户信息
// GET /api/v1/profile
func (h *AuthHandler) GetProfile(c *gin.Context) {
	userID := middleware.GetUserID(c)
	isAdmin := middleware.GetIsAdmin(c)

	var username string
	var nickname string

	if isAdmin {
		username = h.cfg.AdminUsername
	} else if strings.HasPrefix(userID, "user_") {
		username = strings.TrimPrefix(userID, "user_")
	} else {
		username = userID
	}

	// 从数据库查询详细信息
	if h.db != nil {
		u, err := store.GetUserByUsername(h.db, username)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "服务器内部错误"})
			return
		}
		if u != nil {
			c.JSON(http.StatusOK, gin.H{
				"user_id":    userID,
				"username":   u.Username,
				"nickname":   u.Nickname,
				"is_admin":   u.IsAdmin,
				"created_at": u.CreatedAt.UTC().Format(time.RFC3339),
			})
			return
		}
		// 用户不存在（可能 admin 未迁移或数据库问题）
		if !isAdmin {
			c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
			return
		}
	}

	// 数据库不可用时的回退
	if isAdmin {
		nickname = h.cfg.AdminNickname
		if nickname == "" {
			nickname = "管理员"
		}
		c.JSON(http.StatusOK, gin.H{
			"user_id":    userID,
			"username":   username,
			"nickname":   nickname,
			"is_admin":   true,
			"created_at": nil,
		})
		return
	}

	c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
}
