<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('resource_history', function (Blueprint $table) {
            $table->id();
            $table->foreignId('account_id')->constrained('accounts')->cascadeOnDelete();
            $table->decimal('cpu_percent', 5, 2)->default(0)->comment('Instantaneous CPU usage from cgroup');
            $table->unsignedBigInteger('memory_bytes')->default(0)->comment('memory.current at sample time');
            $table->unsignedBigInteger('disk_io_read_bytes')->default(0)->comment('Cumulative rbytes from io.stat');
            $table->unsignedBigInteger('disk_io_write_bytes')->default(0)->comment('Cumulative wbytes from io.stat');
            $table->unsignedBigInteger('network_in_bytes')->default(0)->comment('Cumulative net rx (best-effort, 0 if not available)');
            $table->unsignedBigInteger('network_out_bytes')->default(0)->comment('Cumulative net tx (best-effort, 0 if not available)');
            $table->unsignedInteger('process_count')->default(0);
            $table->timestamp('recorded_at')->useCurrent();
            $table->timestamp('created_at')->useCurrent();

            // Optimised for time-range queries per account
            $table->index(['account_id', 'recorded_at']);
            $table->index('recorded_at');
        });
    }

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