package main

import (
    "database/sql/driver"
    "time"
    "gorm.io/gorm"
)

type JSON []byte

// Global database handle shared across the application
var db *gorm.DB

func (j JSON) Value() (driver.Value, error) {
	if j == nil {
		return nil, nil
	}
	return string(j), nil
}

func (j *JSON) Scan(value interface{}) error {
	if value == nil {
		*j = nil
		return nil
	}
	switch v := value.(type) {
	case []byte:
		*j = JSON(v)
	case string:
		*j = JSON(v)
	}
	return nil
}

func (j JSON) MarshalJSON() ([]byte, error) {
	if j == nil {
		return []byte("null"), nil
	}
	return j, nil
}

func (j *JSON) UnmarshalJSON(data []byte) error {
	*j = JSON(data)
	return nil
}

type Server struct {
	ID          uint   `gorm:"primaryKey"`
	Name        string `gorm:"uniqueIndex;not null"`
	Mode        string `gorm:"not null;default:forward"`
	PublicKey   string `gorm:"not null"`
	Endpoint    string
	Webhooks    []Webhook `gorm:"foreignKey:ServerID"`
	Peers       []Peer    `gorm:"foreignKey:ServerID"`
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

type Peer struct {
    ID            uint      `gorm:"primaryKey"`
    ServerID      uint      `gorm:"not null;index"`
    PublicKey     string    `gorm:"uniqueIndex;not null"`
    IP            string    `gorm:"not null"`
    AllowAccess   JSON      `gorm:"type:text"`
    AllowInternet bool      `gorm:"default:false"`
    CreatedAt     time.Time
    UpdatedAt     time.Time
    // ExpiresAt defines when this peer should be considered expired and eligible for auto-deletion
    ExpiresAt     time.Time
    // DataLimitGB defines the monthly data limit per peer (in GB). 0 means unlimited.
    DataLimitGB   int64
    // CurrentDataUsageBytes tracks the amount of data used by this peer (in bytes)
    CurrentDataUsageBytes int64
    // Enabled indicates whether the peer is active. Auto-restrict disables the peer if over the limit.
    Enabled       bool `gorm:"default:true"`
}

type Webhook struct {
	ID               uint      `gorm:"primaryKey"`
	ServerID         uint      `gorm:"index"`
	Name             string    `gorm:"not null"`
	URL              string    `gorm:"not null"`
	Template         string    `gorm:"default:default"`
	CustomBody       string    `gorm:"type:text"`
	DefaultPayload   string    `gorm:"type:text"`
	VerifySSL        bool      `gorm:"default:true"`
	CustomHeaders    JSON      `gorm:"type:text"`
	SubscribedActions JSON     `gorm:"type:text"`
	IsEnabled        bool      `gorm:"default:true"`
	IsGlobal         bool      `gorm:"default:false"`
	CreatedAt        time.Time
	UpdatedAt        time.Time
}

type SMTPSettings struct {
	ID        uint   `gorm:"primaryKey"`
	Enabled   bool   `gorm:"default:false"`
	Server    string `gorm:"default:smtp.gmail.com"`
	Port      int    `gorm:"default:587"`
	UseTLS    bool   `gorm:"default:true"`
	Username  string
	Password  string
	FromEmail string
	FromName  string
	UseAuth   bool `gorm:"default:true"`
}
