package models

import "encoding/json"

// SystemData - Alle Systemdaten die der Agent sendet
type SystemData struct {
	AgentID           string             `json:"agent_id"`
	Hostname          string             `json:"hostname"`
	OPNsenseVersion   string             `json:"opnsense_version"`
	FreeBSDVersion    string             `json:"freebsd_version"`
	UptimeSeconds     int64              `json:"uptime_seconds"`
	Hardware          HardwareInfo       `json:"hardware"`
	CPU               CPUInfo            `json:"cpu"`
	Memory            MemoryInfo         `json:"memory"`
	Disks             []DiskInfo         `json:"disks"`
	NetworkInterfaces []NetworkInterface `json:"network_interfaces"`
	Services          []ServiceInfo      `json:"services"`
	WireGuard         []WireGuardTunnel  `json:"wireguard,omitempty"`
	DHCP              *DHCPInfo          `json:"dhcp,omitempty"`
	Routes            []Route            `json:"routes,omitempty"`
	Gateways          []GatewayInfo      `json:"gateways,omitempty"`
	Certificates      []CertificateInfo  `json:"certificates,omitempty"`
	Plugins           []PluginInfo       `json:"plugins,omitempty"`
	Updates           *UpdateInfo        `json:"updates,omitempty"`
	CronJobs          []CronJob          `json:"cron_jobs,omitempty"`
	License           *LicenseInfo       `json:"license,omitempty"`
	Proxmox           map[string]interface{} `json:"proxmox,omitempty"`
	PBS               map[string]interface{} `json:"pbs,omitempty"`
	Backups           map[string]interface{} `json:"backups,omitempty"`
	Security          *SecurityInfo          `json:"security,omitempty"`
	PFStates          *PFStatesInfo          `json:"pf_states,omitempty"`
	HAProxy           *HAProxyData           `json:"haproxy,omitempty"`
	Caddy             *CaddyData             `json:"caddy,omitempty"`
	// Plattform-spezifische Rohdaten (Windows, Linux, etc.)
	Windows           json.RawMessage        `json:"windows,omitempty"`
	// RawJSON: vollstaendige Rohdaten aus DB (wird im API-Response verwendet)
	RawJSON           json.RawMessage        `json:"-"`
}

type LicenseInfo struct {
	IsBusinessEdition bool   `json:"is_business_edition"`
	ProductName       string `json:"product_name,omitempty"`
	Subscription      string `json:"subscription,omitempty"`
	ValidTo           string `json:"valid_to,omitempty"`
	DaysRemaining     int    `json:"days_remaining,omitempty"`
}

type WireGuardTunnel struct {
	Interface  string           `json:"interface"`
	PublicKey  string           `json:"public_key"`
	ListenPort int             `json:"listen_port"`
	Peers      []WireGuardPeer `json:"peers"`
}

type WireGuardPeer struct {
	PublicKey       string   `json:"public_key"`
	Endpoint        string   `json:"endpoint"`
	AllowedIPs      []string `json:"allowed_ips"`
	LatestHandshake int64    `json:"latest_handshake_epoch"`
	HandshakeAge    string   `json:"handshake_age"`
	TransferRx      int64    `json:"transfer_rx_bytes"`
	TransferTx      int64    `json:"transfer_tx_bytes"`
	Keepalive       int      `json:"persistent_keepalive"`
	Status          string   `json:"status"`
}

type DHCPInfo struct {
	Server string      `json:"server"`
	Leases []DHCPLease `json:"leases"`
}

type DHCPLease struct {
	IP       string `json:"ip"`
	MAC      string `json:"mac"`
	Hostname string `json:"hostname"`
	Start    string `json:"start,omitempty"`
	End      string `json:"end,omitempty"`
	Status   string `json:"status"`
	Pool     string `json:"pool,omitempty"`
}

type HardwareInfo struct {
	Manufacturer string `json:"manufacturer"`
	Model        string `json:"model"`
	Serial       string `json:"serial"`
	BIOSVersion  string `json:"bios_version"`
}

type CPUInfo struct {
	Model        string  `json:"model"`
	Cores        int     `json:"cores"`
	Threads      int     `json:"threads"`
	FreqMHz      int     `json:"freq_mhz"`
	UsagePercent float64 `json:"usage_percent"`
}

type MemoryInfo struct {
	TotalBytes int64 `json:"total_bytes"`
	UsedBytes  int64 `json:"used_bytes"`
	FreeBytes  int64 `json:"free_bytes"`
}

type DiskInfo struct {
	Filesystem string `json:"filesystem"`
	TotalBytes int64  `json:"total_bytes"`
	UsedBytes  int64  `json:"used_bytes"`
	FreeBytes  int64  `json:"free_bytes"`
	MountPoint string `json:"mount_point"`
}

type NetworkInterface struct {
	Name    string `json:"name"`
	Role    string `json:"role"`
	IP      string `json:"ip"`
	MAC     string `json:"mac"`
	Status  string `json:"status"`
	RxBytes int64  `json:"rx_bytes"`
	TxBytes int64  `json:"tx_bytes"`
}

type ServiceInfo struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Status      string `json:"status"`
}

type Route struct {
	Destination string `json:"destination"`
	Gateway     string `json:"gateway"`
	Flags       string `json:"flags"`
	Interface   string `json:"interface"`
}

type GatewayInfo struct {
	Name    string `json:"name"`
	Address string `json:"address"`
	Status  string `json:"status"`
	Loss    string `json:"loss,omitempty"`
	Delay   string `json:"delay,omitempty"`
	Stddev  string `json:"stddev,omitempty"`
	Monitor string `json:"monitor,omitempty"`
}

type CertificateInfo struct {
	Name      string `json:"name"`
	Subject   string `json:"subject"`
	Issuer    string `json:"issuer"`
	NotBefore string `json:"not_before"`
	NotAfter  string `json:"not_after"`
	DaysLeft  int    `json:"days_left"`
	Serial    string `json:"serial"`
	SAN       string `json:"san,omitempty"`
	KeyUsage  string `json:"key_usage,omitempty"`
	IsCA      bool   `json:"is_ca"`
	Status    string `json:"status"`
	Source    string `json:"source"`
}

type PluginInfo struct {
	Name        string `json:"name"`
	Version     string `json:"version"`
	Description string `json:"description"`
}

type UpdateInfo struct {
	UpdateAvailable bool                `json:"update_available"`
	PendingCount    int                 `json:"pending_count"`
	SecurityCount   int                 `json:"security_count,omitempty"`
	Updates         []PendingUpdateInfo `json:"updates"`
	OPNsenseUpdate  string              `json:"opnsense_update,omitempty"`
}

type PendingUpdateInfo struct {
	Package    string `json:"package"`
	Arch       string `json:"arch,omitempty"`
	CurrentVer string `json:"current_version"`
	NewVer     string `json:"new_version"`
	Repository string `json:"repository,omitempty"`
	Security   bool   `json:"security,omitempty"`
}

type UpdateInfoFull struct {
	UpdateAvailable bool                `json:"update_available"`
	PendingCount    int                 `json:"pending_count"`
	SecurityCount   int                 `json:"security_count,omitempty"`
	Updates         []PendingUpdateInfo `json:"updates"`
}

type CronJob struct {
	Source      string `json:"source"`
	Enabled     bool   `json:"enabled"`
	Minutes     string `json:"minutes"`
	Hours       string `json:"hours"`
	Days        string `json:"days"`
	Months      string `json:"months"`
	Weekdays    string `json:"weekdays"`
	Command     string `json:"command"`
	Parameters  string `json:"parameters,omitempty"`
	Who         string `json:"who,omitempty"`
	Description string `json:"description,omitempty"`
	UUID        string `json:"uuid,omitempty"`
	Origin      string `json:"origin,omitempty"`
	Schedule    string `json:"schedule"`
}

type SecurityInfo struct {
	SSHLogins    []SecurityLoginEvent `json:"ssh_logins"`
	WebGUILogins []SecurityLoginEvent `json:"webgui_logins"`
	Sessions     []SecuritySession    `json:"sessions"`
	Summary      SecuritySummary      `json:"summary"`
}

type SecurityLoginEvent struct {
	Timestamp string `json:"timestamp"`
	User      string `json:"user"`
	Source    string `json:"source"`
	Port      string `json:"port"`
	Method    string `json:"method"`
	Status    string `json:"status"`
	Key       string `json:"key,omitempty"`
}

type SecuritySession struct {
	User     string `json:"user"`
	TTY      string `json:"tty"`
	From     string `json:"from"`
	Login    string `json:"login"`
	Logout   string `json:"logout"`
	Duration string `json:"duration"`
}

type SecuritySummary struct {
	TotalAccepted int    `json:"total_accepted"`
	TotalFailed   int    `json:"total_failed"`
	UniqueIPs     int    `json:"unique_ips"`
	UniqueUsers   int    `json:"unique_users"`
	LastLogin     string `json:"last_login"`
}

type PFStatesInfo struct {
	CurrentEntries int     `json:"current_entries"`
	HardLimit      int     `json:"hard_limit"`
	SearchRate     float64 `json:"search_rate"`
	InsertRate     float64 `json:"insert_rate"`
	RemovalRate    float64 `json:"removal_rate"`
	MatchRate      float64 `json:"match_rate"`
}

type HAProxyInfo struct {
	Uptime       string `json:"uptime"`
	CurrentConns int    `json:"current_conns"`
	TotalConns   int    `json:"total_conns"`
	TotalReqs    int    `json:"total_requests"`
	CurrentSSL   int    `json:"current_ssl"`
	TotalSSL     int    `json:"total_ssl"`
	MaxConns     int    `json:"max_conns"`
}

type HAProxyEntry struct {
	ProxyName       string `json:"proxy_name"`
	ServerName      string `json:"server_name"`
	Type            string `json:"type"`
	Status          string `json:"status"`
	CurrentSessions int    `json:"current_sessions"`
	TotalSessions   int    `json:"total_sessions"`
	BytesIn         int64  `json:"bytes_in"`
	BytesOut        int64  `json:"bytes_out"`
	RequestsTotal   int    `json:"requests_total"`
	ErrorsReq       int    `json:"errors_req"`
	ErrorsConn      int    `json:"errors_conn"`
	ErrorsResp      int    `json:"errors_resp"`
}

type HAProxyData struct {
	Info    HAProxyInfo    `json:"info"`
	Entries []HAProxyEntry `json:"entries"`
}

type CaddySite struct {
	Domain   string `json:"domain"`
	Upstream string `json:"upstream"`
	TLS      bool   `json:"tls"`
}

type CaddyUpstream struct {
	Address     string `json:"address"`
	NumRequests int    `json:"num_requests"`
	Fails       int    `json:"fails"`
	Healthy     bool   `json:"healthy"`
}

type CaddyData struct {
	Version   string          `json:"version"`
	Sites     []CaddySite     `json:"sites"`
	Upstreams []CaddyUpstream `json:"upstreams,omitempty"`
}

// HeartbeatRequest
type HeartbeatRequest struct {
	AgentID      string          `json:"agent_id"`
	AgentVersion string          `json:"agent_version,omitempty"`
	Platform     string          `json:"platform,omitempty"`
	SystemData   json.RawMessage `json:"system_data"`
}

// HeartbeatResponse
type HeartbeatResponse struct {
	Message         string `json:"message"`
	UpdateAvailable bool   `json:"update_available,omitempty"`
	UpdateVersion   string `json:"update_version,omitempty"`
	UpdateHash      string `json:"update_hash,omitempty"`
}
