<?php

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

/**
 * One row per instance per day.
 *
 * instance_traffic keeps a single row per BILLING period, which is what the
 * allowance needs — but it means there is no series to draw, and the customer
 * panel could only ever show a number. Storage consumption was not sampled at
 * all, so the panel stated the contractual allowance and nothing about what is
 * actually in use.
 *
 * A day is the right grain: fine enough for a fortnight of trend, coarse enough
 * that a year of an instance is 365 rows.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('instance_metrics', function (Blueprint $table) {
            $table->id();
            $table->foreignId('instance_id')->constrained()->cascadeOnDelete();
            $table->date('day');

            // Nullable, and deliberately: a sample that could not be taken must
            // be distinguishable from a sample that read zero. Charting a failed
            // read as 0 GB is how a panel tells a customer their data is gone.
            $table->unsignedBigInteger('disk_used_bytes')->nullable();
            $table->unsignedBigInteger('disk_total_bytes')->nullable();
            $table->unsignedBigInteger('rx_bytes')->default(0);
            $table->unsignedBigInteger('tx_bytes')->default(0);
            $table->timestamps();

            // The sampler runs more often than daily and accumulates into the
            // current day's row; the constraint is what makes that safe under
            // two workers.
            $table->unique(['instance_id', 'day']);
        });
    }

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