package controllers

import (
	"ems-backend/models"
	"net/http"
	"time"

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

func GetAlarms(c *gin.Context) {
	var alarms []models.AlarmLog
	status := c.Query("status")
	
	query := models.DB.Order("start_time desc")
	if status != "" {
		query = query.Where("status = ?", status)
	}
	
	if err := query.Find(&alarms).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 修复时区问题：同综合大屏逻辑，强制修正为 Asia/Shanghai
	loc, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		loc = time.FixedZone("CST", 8*3600)
	}

	for i := range alarms {
		t := alarms[i].StartTime
		// 保持数值不变，强制指定时区
		alarms[i].StartTime = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), loc)
	}

	c.JSON(http.StatusOK, alarms)
}

func AcknowledgeAlarm(c *gin.Context) {
	id := c.Param("id")
	var alarm models.AlarmLog
	
	if err := models.DB.First(&alarm, "id = ?", id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Alarm not found"})
		return
	}
	
	alarm.Status = "ACKED"
	models.DB.Save(&alarm)
	
	c.JSON(http.StatusOK, alarm)
}

// CreateAlarm is mainly for testing or internal system calls
func CreateAlarm(c *gin.Context) {
	var alarm models.AlarmLog
	if err := c.ShouldBindJSON(&alarm); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	alarm.StartTime = time.Now()
	alarm.Status = "ACTIVE"
	
	if err := models.DB.Create(&alarm).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusCreated, alarm)
}

