package models

import (
	"time"

	"github.com/google/uuid"
	"gorm.io/datatypes"
	"gorm.io/gorm"
)

// IntegrationSource 接入源
type IntegrationSource struct {
	ID         uuid.UUID      `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"ID"`
	Name       string         `gorm:"type:varchar(50)" json:"Name"`
	DriverType string         `gorm:"type:varchar(20)" json:"DriverType"` // HA, MODBUS
	Status     string         `gorm:"type:varchar(20)" json:"Status"`
	Config     datatypes.JSON `gorm:"type:jsonb" json:"Config"`       // IP, Token
	DeviceCount int64          `gorm:"-" json:"DeviceCount"`           // 关联设备数量
}

// Device 设备资产
type Device struct {
	ID               uuid.UUID      `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
	SourceID         uuid.UUID      `gorm:"type:uuid"`
	ExternalID       string         `gorm:"type:varchar(100)"`
	Name             string         `gorm:"type:varchar(100)"`
	DeviceType       string         `gorm:"type:varchar(50)"` // ELECTRIC, WATER, GAS, INDUSTRIAL_ELECTRIC
	LocationID       *uuid.UUID     `gorm:"type:uuid"`        // 关联空间
	AttributeMapping datatypes.JSON `gorm:"type:jsonb"`       // 属性映射
	Status           string         `gorm:"type:varchar(20)"` // NORMAL, INACTIVE
}

// SysLocation 空间拓扑
type SysLocation struct {
	ID       uuid.UUID  `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
	ParentID *uuid.UUID `gorm:"type:uuid"`
	Name     string     `gorm:"type:varchar(50)"`
	Type     string     `gorm:"type:varchar(20)"` // PARK, BUILDING, FLOOR, ROOM
}

// AlarmLog 告警记录
type AlarmLog struct {
	ID        uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
	DeviceID  uuid.UUID `gorm:"type:uuid"`
	Type      string    `gorm:"type:varchar(50)"`
	Content   string    `gorm:"type:text"`
	Status    string    `gorm:"type:varchar(20)"` // ACTIVE, ACKED, RESOLVED
	StartTime time.Time `gorm:"type:timestamp"`
}

// SysOperLog 操作日志
type SysOperLog struct {
	ID      uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
	UserID  uuid.UUID `gorm:"type:uuid"`
	Action  string    `gorm:"type:varchar(50)"` // TURN_ON, UPDATE_CONFIG
	Target  string    `gorm:"type:varchar(100)"`
	Result  bool      `gorm:"type:boolean"`
	Time    time.Time `gorm:"type:timestamp"`
}

// InspectionLedger 巡检台账
type InspectionLedger struct {
	ID              uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
	DeviceID        uuid.UUID `gorm:"type:uuid"`
	InspectorID     uuid.UUID `gorm:"type:uuid"`
	Status          string    `gorm:"type:varchar(20)"` // NORMAL, ABNORMAL
	CalibratedPower float64   `gorm:"type:numeric(10,2)"`
	CheckTime       time.Time `gorm:"type:timestamp"`
}

// SysRole 角色
type SysRole struct {
	ID                uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
	Name              string    `gorm:"type:varchar(50)"`
	RoleKey           string    `gorm:"type:varchar(50)"` // admin, common
	DataScope         string    `gorm:"type:varchar(20)"` // 1:ALL, 4:SELF
	MenuCheckStrictly bool      `gorm:"default:true"`
	Status            string    `gorm:"type:varchar(1)"` // 0:Normal, 1:Disable
}

// SysUserRole 用户角色关联
type SysUserRole struct {
	UserID uuid.UUID `gorm:"type:uuid;primary_key"`
	RoleID uuid.UUID `gorm:"type:uuid;primary_key"`
}

// SysConfig 系统配置
type SysConfig struct {
	ConfigID    int    `gorm:"primary_key;autoIncrement"`
	ConfigKey   string `gorm:"type:varchar(100);unique"`
	ConfigValue string `gorm:"type:text"`
	ConfigType  string `gorm:"type:varchar(10)"` // Y/N
	Remark      string `gorm:"type:varchar(500)"`
}

// User 用户
type User struct {
	ID          uuid.UUID  `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
	Username    string     `gorm:"type:varchar(50);unique"`
	Password    string     `gorm:"type:varchar(100)"` // In production, use hash
	Role        string     `gorm:"type:varchar(20)"`  // ADMIN, USER (Deprecated, use SysUserRole)
	Name        string     `gorm:"type:varchar(50)"`
	Email       *string    `gorm:"type:varchar(100);unique"`
	PhoneNumber *string    `gorm:"type:varchar(20);unique"`
	Status      string     `gorm:"type:varchar(1)"` // 0:Normal, 1:Disable
	CreatedAt   time.Time  `gorm:"autoCreateTime"`
}

// AlarmRuleBinding 告警规则绑定关系
type AlarmRuleBinding struct {
	RuleID     uuid.UUID `gorm:"type:uuid;primary_key"`
	TargetID   uuid.UUID `gorm:"type:uuid;primary_key"` // DeviceID or LocationID
	TargetType string    `gorm:"type:varchar(20)"`      // "DEVICE" or "SPACE"
}

// AlarmRule 告警规则配置
type AlarmRule struct {
	ID            uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
	Name          string    `gorm:"type:varchar(100)" json:"name"`
	
	// Legacy fields for compatibility with existing DB schema
	TargetType    string    `gorm:"type:varchar(20)" json:"-"` 
	TargetID      uuid.UUID `gorm:"type:uuid" json:"-"`

	Metric        string    `gorm:"type:varchar(50)" json:"metric"`      // voltage, current, power...
	Operator      string    `gorm:"type:varchar(10)" json:"operator"`    // >, <, >=, <=, =
	Threshold     float64   `gorm:"type:numeric(10,2)" json:"threshold"`
	Duration      int       `gorm:"default:0" json:"duration"`         // 持续时间(秒)
	SilencePeriod int       `gorm:"default:300" json:"silence_period"` // 静默周期(秒)
	Priority      string    `gorm:"type:varchar(20)" json:"priority"`  // CRITICAL, WARNING, INFO
	Message       string    `gorm:"type:varchar(255)" json:"message"`
	Enabled       bool      `gorm:"default:true" json:"enabled"`
	CreatedAt     time.Time `gorm:"autoCreateTime" json:"created_at"`
	
	// Virtual field for API handling
	Bindings []AlarmRuleBinding `gorm:"foreignKey:RuleID" json:"bindings,omitempty"`
}

func TableName(name string) func(tx *gorm.DB) *gorm.DB {
	return func(tx *gorm.DB) *gorm.DB {
		return tx.Table(name)
	}
}

