package adminpush

import (
	"encoding/json"
	"time"
)

// ── 数据库模型 ──

type pushChannel struct {
	ID        uint64          `gorm:"primaryKey" json:"id"`
	Name      string          `gorm:"size:64;not null" json:"name"`
	Type      string          `gorm:"size:32;not null" json:"type"`
	Config    json.RawMessage `gorm:"type:json;not null" json:"config"`
	Enabled   bool            `gorm:"not null;default:true" json:"enabled"`
	CreatedAt time.Time       `json:"created_at"`
	UpdatedAt time.Time       `json:"updated_at"`
}

func (pushChannel) TableName() string { return "push_channels" }

type pushRule struct {
	ID              uint64    `gorm:"primaryKey" json:"id"`
	Event           string    `gorm:"size:64;not null;uniqueIndex" json:"event"`
	Enabled         bool      `gorm:"not null;default:true" json:"enabled"`
	Threshold       int       `gorm:"not null;default:5" json:"threshold"`
	MessageTemplate string    `gorm:"size:255;not null;default:''" json:"message_template"`
	CreatedAt       time.Time `json:"created_at"`
	UpdatedAt       time.Time `json:"updated_at"`
}

func (pushRule) TableName() string { return "push_rules" }

// ── DTO ──

type ChannelDTO struct {
	ID        uint64          `json:"id"`
	Name      string          `json:"name"`
	Type      string          `json:"type"`
	Config    json.RawMessage `json:"config"`
	Enabled   bool            `json:"enabled"`
	CreatedAt time.Time       `json:"created_at"`
	UpdatedAt time.Time       `json:"updated_at"`
}

type RuleDTO struct {
	ID              uint64    `json:"id"`
	Event           string    `json:"event"`
	Enabled         bool      `json:"enabled"`
	Threshold       int       `json:"threshold"`
	MessageTemplate string    `json:"message_template"`
	CreatedAt       time.Time `json:"created_at"`
	UpdatedAt       time.Time `json:"updated_at"`
}

// ── 请求 ──

type CreateChannelRequest struct {
	Name   string          `json:"name" binding:"required"`
	Type   string          `json:"type" binding:"required"`
	Config json.RawMessage `json:"config" binding:"required"`
}

type UpdateChannelRequest struct {
	Name    *string          `json:"name"`
	Config  *json.RawMessage `json:"config"`
	Enabled *bool            `json:"enabled"`
}

type UpdateRuleRequest struct {
	Enabled         *bool   `json:"enabled"`
	Threshold       *int    `json:"threshold"`
	MessageTemplate *string `json:"message_template"`
}

// ── 转换 ──

func toChannelDTO(row pushChannel) ChannelDTO {
	return ChannelDTO{
		ID:        row.ID,
		Name:      row.Name,
		Type:      row.Type,
		Config:    row.Config,
		Enabled:   row.Enabled,
		CreatedAt: row.CreatedAt,
		UpdatedAt: row.UpdatedAt,
	}
}

func toRuleDTO(row pushRule) RuleDTO {
	return RuleDTO{
		ID:              row.ID,
		Event:           row.Event,
		Enabled:         row.Enabled,
		Threshold:       row.Threshold,
		MessageTemplate: row.MessageTemplate,
		CreatedAt:       row.CreatedAt,
		UpdatedAt:       row.UpdatedAt,
	}
}
