package logging

import (
	"time"

	log "github.com/sirupsen/logrus"
)

// 结构化日志示例

// LogUserAction 记录用户操作日志
func LogUserAction(userID uint, action string, requestID string, details map[string]interface{}) {
	fields := log.Fields{
		"user_id":    userID,
		"action":     action,
		"request_id": requestID,
		"timestamp":  time.Now().Format(time.RFC3339),
	}

	// 合并详情字段
	for k, v := range details {
		fields[k] = v
	}

	log.WithFields(fields).Info("用户操作")
}

// LogAPIRequest 记录 API 请求日志
func LogAPIRequest(requestID string, method string, path string, statusCode int, duration time.Duration, userID uint) {
	log.WithFields(log.Fields{
		"request_id":  requestID,
		"method":      method,
		"path":        path,
		"status_code": statusCode,
		"duration_ms": duration.Milliseconds(),
		"user_id":     userID,
	}).Info("API请求")
}

// LogError 记录错误日志
func LogError(requestID string, err error, context map[string]interface{}) {
	fields := log.Fields{
		"request_id": requestID,
		"error":      err.Error(),
	}

	for k, v := range context {
		fields[k] = v
	}

	log.WithFields(fields).Error("发生错误")
}

// 敏感信息脱敏工具

// MaskPhone 手机号脱敏
func MaskPhone(phone string) string {
	if len(phone) >= 11 {
		return phone[:3] + "****" + phone[7:]
	}
	return "****"
}

// MaskEmail 邮箱脱敏
func MaskEmail(email string) string {
	atIndex := -1
	for i, c := range email {
		if c == '@' {
			atIndex = i
			break
		}
	}
	if atIndex > 2 {
		return email[:2] + "***" + email[atIndex:]
	}
	return "***@***"
}

// MaskIDCard 身份证号脱敏
func MaskIDCard(idCard string) string {
	if len(idCard) >= 18 {
		return idCard[:6] + "********" + idCard[14:]
	}
	return "******"
}
