package model

import (
	"database/sql/driver"
	"encoding/json"
	"strings"
)

type HostList []string

func (h HostList) Value() (driver.Value, error) {
	return strings.Join(h, ","), nil
}

func (h *HostList) Scan(src interface{}) error {
	*h = strings.Split(src.(string), ",")
	return nil
}

type Waf struct {
	ID          uint     `gorm:"column:id;primaryKey;autoIncrement"`
	GatewayName string   `gorm:"column:gateway_name"`
	Port        int      `gorm:"column:port"`
	Namespace   string   `gorm:"column:namespace"`
	RegionCode  string   `gorm:"column:region_code"`
	Host        HostList `gorm:"column:host"`
}

func (Waf) TableName() string {
	return "waf"
}

type WafRule struct {
	ID          int    `json:"id"`
	CategoryID  string `gorm:"column:category_id"`
	Level       int    `json:"level"`
	Status      int    `gorm:"column:status"`
	Name        string `json:"name"`
	Type        string `json:"type"`
	Description string `json:"description"`
	Expr        string `json:"expr"`
	Mode        string `json:"mode"`
}

func (WafRule) TableName() string {
	return "waf_rules"
}

type WafRuleCategory struct {
	ID            string    `gorm:"column:id;primaryKey;autoIncrement"`
	CategoryID    string    `gorm:"column:category_id"`
	CategoryEN    string    `gorm:"column:category_en"`
	CategoryZH    string    `gorm:"column:category_zh"`
	DescriptionEN string    `gorm:"column:description_en"`
	DescriptionZH string    `gorm:"column:description_zh"`
	Status        int       `gorm:"column:status"`
	Rules         []WafRule `gorm:"column:rules"`
}

func (WafRuleCategory) TableName() string {
	return "waf_rule_categories"
}

func (r *WafRuleCategory) Scan(src interface{}) error {
	err := json.Unmarshal(src.([]byte), r)
	if err != nil {
		return err
	}
	return nil
}

func (r WafRuleCategory) Value() (driver.Value, error) {
	return json.Marshal(r)
}
