package controllers

import (
	"ems-backend/models"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"gorm.io/gorm"
    "net/http"
    "strconv"
)

// AlarmRuleRequest 用于接收前端参数，包含绑定信息
type AlarmRuleRequest struct {
	models.AlarmRule
	BindingIds  []string `json:"binding_ids"`  // 绑定的 ID 列表 (DeviceID 或 LocationID)
	BindingType string   `json:"binding_type"` // DEVICE or SPACE
}

// BatchDeleteRequest 批量删除请求
type BatchDeleteRequest struct {
	Ids []string `json:"ids"`
}

// CreateAlarmRule 创建告警规则
func CreateAlarmRule(c *gin.Context) {
	var req AlarmRuleRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 1. Check for duplicate name
	var count int64
	models.DB.Model(&models.AlarmRule{}).Where("name = ?", req.Name).Count(&count)
	if count > 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Rule name already exists"})
		return
	}

	// 2. Create Rule
	// Ensure ID is generated
	if req.AlarmRule.ID == uuid.Nil {
		req.AlarmRule.ID = uuid.New()
	}
	
	err := models.DB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Create(&req.AlarmRule).Error; err != nil {
			return err
		}

		// 2. Create Bindings
		if len(req.BindingIds) > 0 {
			var bindings []models.AlarmRuleBinding
			for _, bid := range req.BindingIds {
				targetUUID, err := uuid.Parse(bid)
				if err != nil {
					continue
				}
				bindings = append(bindings, models.AlarmRuleBinding{
					RuleID:     req.AlarmRule.ID,
					TargetID:   targetUUID,
					TargetType: req.BindingType,
				})
			}
			if len(bindings) > 0 {
				if err := tx.Create(&bindings).Error; err != nil {
					return err
				}
			}
		}
		return nil
	})

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create alarm rule: " + err.Error()})
		return
	}

	c.JSON(http.StatusOK, req.AlarmRule)
}

// GetAlarmRules 获取告警规则列表
func GetAlarmRules(c *gin.Context) {
	var rules []models.AlarmRule
	var total int64
	
	// Parse Pagination
	page := 1
	if c.Query("page") != "" {
		if p, err := strconv.ParseInt(c.Query("page"), 10, 64); err == nil && p > 0 {
			page = int(p)
		}
	}

	pageSize := 10
	if c.Query("page_size") != "" {
		if ps, err := strconv.ParseInt(c.Query("page_size"), 10, 64); err == nil && ps > 0 {
			pageSize = int(ps)
		}
	}

	offset := (page - 1) * pageSize

	// Query
	query := models.DB.Model(&models.AlarmRule{})

	// Search by name
	if name := c.Query("name"); name != "" {
		query = query.Where("name LIKE ?", "%"+name+"%")
	}
	
	// Search by enabled
	if enabled := c.Query("enabled"); enabled != "" {
		if b, err := strconv.ParseBool(enabled); err == nil {
			query = query.Where("enabled = ?", b)
		}
	}

	// Count total
	query.Count(&total)

	// Fetch data with pagination
	if err := query.Offset(offset).Limit(pageSize).Preload("Bindings").Find(&rules).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch alarm rules"})
		return
	}
	
	if rules == nil {
		rules = []models.AlarmRule{}
	}

	c.JSON(http.StatusOK, gin.H{
		"data":  rules,
		"total": total,
	})
}

// UpdateAlarmRule 更新告警规则
func UpdateAlarmRule(c *gin.Context) {
	id := c.Param("id")
	var req AlarmRuleRequest
	
	// Check exist
	var existingRule models.AlarmRule
	if err := models.DB.First(&existingRule, "id = ?", id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Alarm rule not found"})
		return
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// Don't modify bindings if BindingIds is empty/nil? 
	// Issue: "Update Enable" only sends {enabled: false}, so BindingIds is empty/nil.
	// But "Edit Config" sends empty array if clearing selection.
	// We need to distinguish between "Update Fields Only" vs "Update Config with Bindings".
	// Simple fix: If BindingIds is nil (not present in JSON), don't update bindings?
	// But Go structs default to nil/empty slice.
	// Better: Check if we are only patching. For now, let's assume if it's a PATCH-like behavior (e.g. toggle enable), we should preserve bindings.
	// But here we are using PUT.
	// Let's reload existing bindings if req.BindingIds is empty AND we want to preserve them?
	// Actually, the toggle in frontend calls updateAlarmRule(id, {enabled: val}). It DOES NOT send binding_ids.
	// So req.BindingIds will be empty slice. This causes bindings to be deleted.
	
	// FIX: If we detect this is a partial update (e.g. only enabled is set, or binding_ids is missing/nil), handle gracefully.
	// However, standard Update usually implies full replace or we need logic.
	
	// Let's recover existing bindings if the request didn't explicitly include them?
	// Limitation: Go struct doesn't easily show "missing" vs "empty".
	// We can check binding_type. If binding_type is empty, assume we are not updating bindings.

	// 1. Check for duplicate name (exclude self)
	if req.Name != "" { // Only check if name is being updated
		var count int64
		models.DB.Model(&models.AlarmRule{}).Where("name = ? AND id != ?", req.Name, existingRule.ID).Count(&count)
		if count > 0 {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Rule name already exists"})
			return
		}
	}

	err := models.DB.Transaction(func(tx *gorm.DB) error {
		// 1. Update Rule Fields
		updateData := req.AlarmRule
		updateData.ID = existingRule.ID
		updateData.CreatedAt = existingRule.CreatedAt // preserve
		
		if err := tx.Save(&updateData).Error; err != nil {
			return err
		}

		// 2. Update Bindings ONLY if BindingType is provided (indicating a config update)
		// Or if we specifically want to support clearing bindings, we need a flag.
		// For the toggle enable case, BindingType will be empty string.
		if req.BindingType != "" {
			// Delete old bindings
			if err := tx.Delete(&models.AlarmRuleBinding{}, "rule_id = ?", existingRule.ID).Error; err != nil {
				return err
			}

			// Create new bindings
			if len(req.BindingIds) > 0 {
				var bindings []models.AlarmRuleBinding
				for _, bid := range req.BindingIds {
					targetUUID, err := uuid.Parse(bid)
					if err != nil {
						continue
					}
					bindings = append(bindings, models.AlarmRuleBinding{
						RuleID:     existingRule.ID,
						TargetID:   targetUUID,
						TargetType: req.BindingType,
					})
				}
				if len(bindings) > 0 {
					if err := tx.Create(&bindings).Error; err != nil {
						return err
					}
				}
			}
		}
		return nil
	})

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update alarm rule: " + err.Error()})
		return
	}

	c.JSON(http.StatusOK, req.AlarmRule)
}

// DeleteAlarmRule 删除告警规则
func DeleteAlarmRule(c *gin.Context) {
	id := c.Param("id")
	
	err := models.DB.Transaction(func(tx *gorm.DB) error {
		// 1. Delete Bindings
		if err := tx.Delete(&models.AlarmRuleBinding{}, "rule_id = ?", id).Error; err != nil {
			return err
		}
		// 2. Delete Rule
		if err := tx.Delete(&models.AlarmRule{}, "id = ?", id).Error; err != nil {
			return err
		}
		return nil
	})

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete alarm rule: " + err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Alarm rule deleted successfully"})
}

// BatchDeleteAlarmRules 批量删除告警规则
func BatchDeleteAlarmRules(c *gin.Context) {
	var req BatchDeleteRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if len(req.Ids) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "No IDs provided"})
		return
	}

	err := models.DB.Transaction(func(tx *gorm.DB) error {
		// 1. Delete Bindings
		if err := tx.Delete(&models.AlarmRuleBinding{}, "rule_id IN ?", req.Ids).Error; err != nil {
			return err
		}
		// 2. Delete Rules
		if err := tx.Delete(&models.AlarmRule{}, "id IN ?", req.Ids).Error; err != nil {
			return err
		}
		return nil
	})

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to batch delete alarm rules: " + err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Alarm rules deleted successfully"})
}
