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 RuleCategoryStatus struct {
	CategoryID string `json:"category_id"`
	Status     int    `json:"status"`
}

type RuleCategoryStatusList []RuleCategoryStatus

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

func (r *RuleCategoryStatusList) Scan(src interface{}) error {
	return json.Unmarshal(src.([]byte), r)
}

type WafService 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"`
	Mode               string                 `gorm:"column:mode"`
	RuleNum            int                    `gorm:"column:rule_num"`
	AttackNum          int                    `gorm:"column:attack_num"`
	RuleCategoryStatus RuleCategoryStatusList `gorm:"column:rule_category_status;type:json"`
}

func (WafService) TableName() string {
	return "waf_services"
}

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 RuleList []WafRule

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

func (r *RuleList) Scan(src interface{}) error {
	return json.Unmarshal(src.([]byte), r)
}

type WafRuleCategory struct {
	ID            int      `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         RuleList `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)
}
