<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * Per-server bandwidth observation. Two row types share the table:
 *
 *   1) Raw rows (is_daily_rollup=false) — one per agent push, per interface.
 *      Rate fields (rx_mbps, tx_mbps) computed by the agent as delta over
 *      the push interval. Pruned after 7 days.
 *
 *   2) Daily rollups (is_daily_rollup=true) — one per server per day, with
 *      pre-computed p50/p95/p99 + total bytes for the day. Kept long-term
 *      for trend analysis (cheap; ~30 rows/server/month).
 *
 * The summary endpoint /api/bandwidth/summary reads only rollup rows.
 */
class BandwidthSnapshot extends Model {
    use HasFactory;
    public $timestamps = false;
    protected $fillable = [
        'server_id', 'measured_at', 'interface',
        'rx_bytes_total', 'tx_bytes_total',
        'rx_mbps', 'tx_mbps',
        'rx_mbps_p95_24h', 'tx_mbps_p95_24h',
        // Rollup-only fields:
        'is_daily_rollup',
        'p50_rx_mbps', 'p50_tx_mbps',
        'p99_rx_mbps', 'p99_tx_mbps',
        'samples',
    ];
    protected $casts = [
        'measured_at' => 'datetime',
        'is_daily_rollup' => 'boolean',
    ];
    public function server(): BelongsTo { return $this->belongsTo(Server::class); }
}
