<?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('ai_usage', function (Blueprint $table) {
            $table->id();
            // Nullable for self-hosted (null tenant pool).
            $table->foreignId('tenant_id')->nullable()->constrained('tenants')->nullOnDelete();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
            // Billing-period or calendar-month anchor (YYYY-MM-DD).
            $table->date('period_start')->index();
            // Extensibility seam — 'openai' now; future providers without backfill.
            $table->string('provider_key')->default('openai');
            $table->string('model');
            $table->unsignedInteger('prompt_tokens')->default(0);
            $table->unsignedInteger('completion_tokens')->default(0);
            $table->unsignedInteger('total_tokens')->default(0);
            $table->timestamps();

            // Pool sum: tenant within period. Member sum: tenant+user within period.
            $table->index(['tenant_id', 'period_start']);
            $table->index(['tenant_id', 'user_id', 'period_start']);
        });
    }

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