<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

/**
 * Monthly network usage per instance.
 *
 * One row per instance per calendar month, because that is the unit the quota
 * is sold in and the unit Hetzner bills us in. Proxmox reports counters that
 * are cumulative since the VM last started, so the raw values are kept
 * alongside the total: the difference between two samples is the usage, and a
 * counter that went backwards means the VM restarted rather than that traffic
 * was refunded.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('instance_traffic', function (Blueprint $table) {
            $table->id();
            $table->foreignId('instance_id')->constrained()->cascadeOnDelete();
            $table->string('period', 7);                      // YYYY-MM
            $table->unsignedBigInteger('rx_bytes')->default(0);   // into the VM
            $table->unsignedBigInteger('tx_bytes')->default(0);   // out of the VM — what the quota counts
            $table->unsignedBigInteger('last_netin')->default(0); // raw Proxmox counters
            $table->unsignedBigInteger('last_netout')->default(0);
            $table->timestamp('sampled_at')->nullable();
            // Remembered so a customer is warned once per threshold and not on
            // every collection run.
            $table->unsignedTinyInteger('notified_percent')->default(0);
            $table->boolean('throttled')->default(false);
            $table->timestamp('throttled_at')->nullable();
            $table->timestamps();

            $table->unique(['instance_id', 'period']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('instance_traffic');
    }
};
