package repositories

import (
	"log"
	"time"

	"github.com/niangaodev/art-code/config"
	"github.com/niangaodev/art-code/models"
	"gorm.io/gorm"
)

// GetUserByUsername 根据用户名获取用户
func GetUserByUsername(username string) (*models.User, error) {
	var user models.User
	err := config.DB.Model(&models.User{}).
		Select("users.*, COALESCE(roles.name, users.role) as role").
		Joins("LEFT JOIN roles ON users.role_id = roles.id").
		Where("users.username = ? AND users.deleted_at = ?", username, 0).
		First(&user).Error

	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		log.Printf("Error getting user by username: %v", err)
		return nil, err
	}

	return &user, nil
}

// GetUserByID 根据ID获取用户
func GetUserByID(id uint) (*models.User, error) {
	var user models.User
	err := config.DB.Model(&models.User{}).
		Select("users.*, COALESCE(roles.name, users.role) as role").
		Joins("LEFT JOIN roles ON users.role_id = roles.id").
		Where("users.id = ? AND users.deleted_at = ?", id, 0).
		First(&user).Error

	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		log.Printf("Error getting user by ID: %v", err)
		return nil, err
	}

	return &user, nil
}

// GetUsers 获取所有用户 (分页，支持 keyword / role / isActive 搜索)
func GetUsers(page, pageSize int, keyword, role string, isActive int) ([]models.User, int, error) {
	offset := (page - 1) * pageSize

	query := config.DB.Model(&models.User{}).
		Where("users.deleted_at = ?", 0).
		Joins("LEFT JOIN roles ON users.role_id = roles.id AND roles.deleted_at = 0")

	if keyword != "" {
		like := "%" + keyword + "%"
		query = query.Where("users.username LIKE ? OR users.email LIKE ?", like, like)
	}
	if role != "" {
		query = query.Where("COALESCE(roles.name, users.role) = ?", role)
	}
	if isActive >= 0 {
		query = query.Where("users.is_active = ?", isActive)
	}

	var total int64
	if err := query.Count(&total).Error; err != nil {
		log.Printf("Error getting user count: %v", err)
		return nil, 0, err
	}

	listQuery := config.DB.Model(&models.User{}).
		Where("users.deleted_at = ?", 0).
		Joins("LEFT JOIN roles ON users.role_id = roles.id AND roles.deleted_at = 0")
	if keyword != "" {
		like := "%" + keyword + "%"
		listQuery = listQuery.Where("users.username LIKE ? OR users.email LIKE ?", like, like)
	}
	if role != "" {
		listQuery = listQuery.Where("COALESCE(roles.name, users.role) = ?", role)
	}
	if isActive >= 0 {
		listQuery = listQuery.Where("users.is_active = ?", isActive)
	}

	var users []models.User
	err := listQuery.
		Select("users.*, COALESCE(roles.name, users.role) as role").
		Order("users.created_at DESC").
		Limit(pageSize).
		Offset(offset).
		Find(&users).Error

	if err != nil {
		log.Printf("Error querying users: %v", err)
		return nil, 0, err
	}

	return users, int(total), nil
}

// CreateUser 创建用户
func CreateUser(user *models.User) error {
	// 如果提供了RoleID，确保它有效。如果没有RoleID但有Role name，尝试查找RoleID
	if user.RoleID == 0 && user.Role != "" {
		role, err := GetRoleByName(user.Role)
		if err == nil && role != nil {
			user.RoleID = role.ID
		}
	}

	err := config.DB.Create(user).Error
	if err != nil {
		log.Printf("Error creating user: %v", err)
		return err
	}

	return nil
}

// UpdateUser 更新用户
func UpdateUser(user *models.User) error {
	// 同样尝试解析RoleID
	if user.RoleID == 0 && user.Role != "" {
		role, err := GetRoleByName(user.Role)
		if err == nil && role != nil {
			user.RoleID = role.ID
		}
	}

	updates := map[string]interface{}{
		"username":      user.Username,
		"email":         user.Email,
		"avatar":        user.Avatar,
		"bio":           user.Bio,
		"phone":         user.Phone,
		"wechat":        user.Wechat,
		"wechat_qrcode": user.WechatQrcode,
		"role":          user.Role,
		"is_active":     user.IsActive,
		"updated_at":    time.Now().Unix(),
	}

	if user.RoleID != 0 {
		updates["role_id"] = user.RoleID
	} else {
		updates["role_id"] = nil
	}

	err := config.DB.Model(&models.User{}).
		Where("id = ? AND deleted_at = ?", user.ID, 0).
		Updates(updates).Error
	if err != nil {
		log.Printf("Error updating user: %v", err)
		return err
	}

	return nil
}

// UpdateUserPassword 更新用户密码
func UpdateUserPassword(id uint, passwordHash string) error {
	err := config.DB.Model(&models.User{}).
		Where("id = ? AND deleted_at = ?", id, 0).
		Updates(map[string]interface{}{
			"password_hash": passwordHash,
			"updated_at":    time.Now().Unix(),
		}).Error
	if err != nil {
		log.Printf("Error updating user password: %v", err)
		return err
	}

	return nil
}

// DeleteUser 删除用户 (Soft Delete)
func DeleteUser(id uint) error {
	err := config.DB.Model(&models.User{}).
		Where("id = ?", id).
		Update("deleted_at", time.Now().Unix()).Error
	if err != nil {
		log.Printf("Error deleting user: %v", err)
		return err
	}

	return nil
}

// GetUserCount 获取用户总数
func GetUserCount() (int, error) {
	var count int64
	err := config.DB.Model(&models.User{}).
		Where("deleted_at = ?", 0).
		Count(&count).Error
	if err != nil {
		log.Printf("Error getting user count: %v", err)
		return 0, err
	}

	return int(count), nil
}

// BuildUserResponse 构建用户响应
func BuildUserResponse(user *models.User) *models.UserResponse {
	return &models.UserResponse{
		ID:           user.ID,
		Username:     user.Username,
		Email:        user.Email,
		Avatar:       user.Avatar,
		Bio:          user.Bio,
		Phone:        user.Phone,
		Wechat:       user.Wechat,
		WechatQrcode: user.WechatQrcode,
		RoleID:       user.RoleID,
		Role:         user.Role,
		IsActive:     user.IsActive,
		CreatedAt:    time.Unix(user.CreatedAt, 0).Format("2006-01-02 15:04:05"),
		UpdatedAt:    time.Unix(user.UpdatedAt, 0).Format("2006-01-02 15:04:05"),
	}
}

// BuildUserPublicProfile 构建公开用户资料
func BuildUserPublicProfile(user *models.User) *models.UserPublicProfile {
	return &models.UserPublicProfile{
		ID:           user.ID,
		Username:     user.Username,
		Email:        user.Email,
		Avatar:       user.Avatar,
		Bio:          user.Bio,
		Phone:        user.Phone,
		Wechat:       user.Wechat,
		WechatQrcode: user.WechatQrcode,
	}
}

// UpdateCurrentUserProfile 更新当前用户资料（不含角色/状态）
func UpdateCurrentUserProfile(id uint, req *models.UpdateProfileRequest) error {
	err := config.DB.Model(&models.User{}).
		Where("id = ? AND deleted_at = ?", id, 0).
		Updates(map[string]interface{}{
			"email":         req.Email,
			"avatar":        req.Avatar,
			"bio":           req.Bio,
			"phone":         req.Phone,
			"wechat":        req.Wechat,
			"wechat_qrcode": req.WechatQrcode,
			"updated_at":    time.Now().Unix(),
		}).Error
	if err != nil {
		log.Printf("Error updating user profile: %v", err)
		return err
	}
	return nil
}

// BuildUsersResponse 构建用户列表响应
func BuildUsersResponse(users []models.User) []models.UserResponse {
	var responses []models.UserResponse
	for _, user := range users {
		responses = append(responses, *BuildUserResponse(&user))
	}
	return responses
}
