<?php

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

return new class extends Migration
{
    /**
     * Capture token usage and rate-limit headers from token-metering
     * providers (today: Anthropic). These columns let us see the
     * cumulative input-tokens-per-minute trajectory directly in
     * api_logs rather than inferring it from request counts.
     */
    public function up(): void
    {
        Schema::table('api_logs', function (Blueprint $table) {
            $table->unsignedInteger('input_tokens')->nullable()->after('response_body')
                ->comment('Input tokens billed (Anthropic usage.input_tokens). NULL for providers that do not report usage.');
            $table->unsignedInteger('output_tokens')->nullable()->after('input_tokens')
                ->comment('Output tokens billed (Anthropic usage.output_tokens).');
            $table->unsignedInteger('cache_read_tokens')->nullable()->after('output_tokens')
                ->comment('Cache-hit tokens (Anthropic usage.cache_read_input_tokens). Do not count toward ITPM on most models.');
            $table->unsignedInteger('cache_write_tokens')->nullable()->after('cache_read_tokens')
                ->comment('Cache-write tokens (Anthropic usage.cache_creation_input_tokens). Count toward ITPM.');
            $table->unsignedInteger('ratelimit_remaining')->nullable()->after('cache_write_tokens')
                ->comment('Provider-reported input-tokens remaining in the rolling window (anthropic-ratelimit-input-tokens-remaining).');
            $table->dateTime('ratelimit_reset_at')->nullable()->after('ratelimit_remaining')
                ->comment('When the input-tokens bucket will be fully replenished (anthropic-ratelimit-input-tokens-reset, RFC 3339).');
        });
    }

    public function down(): void
    {
        Schema::table('api_logs', function (Blueprint $table) {
            $table->dropColumn([
                'input_tokens',
                'output_tokens',
                'cache_read_tokens',
                'cache_write_tokens',
                'ratelimit_remaining',
                'ratelimit_reset_at',
            ]);
        });
    }
};
