<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('reputation_scores', function (Blueprint $table) {
            $table->id();
            $table->foreignId('brand_id')->constrained()->onDelete('cascade');
            
            // Overall score (0-100)
            $table->decimal('score', 5, 2)->default(0);
            
            // Sub-scores (0-100 each)
            $table->decimal('sentiment_score', 5, 2)->default(0);
            $table->decimal('responsiveness_score', 5, 2)->default(0);
            $table->decimal('trust_score', 5, 2)->default(0);
            $table->decimal('compliance_score', 5, 2)->default(0);
            $table->decimal('growth_score', 5, 2)->default(0);
            
            // Timeframe for this calculation
            $table->enum('timeframe', ['7', '30', '90'])->default('30');
            $table->timestamp('period_start');
            $table->timestamp('period_end');
            
            // AI processing metadata
            $table->string('ai_job_id')->nullable();
            $table->text('ai_explanation')->nullable(); // 3 bullet points
            $table->json('calculation_metadata')->nullable(); // Raw data used
            
            // Score change tracking
            $table->decimal('previous_score', 5, 2)->nullable();
            $table->decimal('score_change', 5, 2)->default(0);
            $table->decimal('score_change_percentage', 5, 2)->default(0);
            
            // Status and alerts
            $table->enum('status', ['calculating', 'completed', 'failed'])->default('calculating');
            $table->boolean('alert_triggered')->default(false);
            $table->text('alert_reason')->nullable();
            
            $table->timestamps();
            
            // Indexes
            $table->index(['brand_id', 'created_at']);
            $table->index(['brand_id', 'timeframe']);
            $table->index('score');
            $table->index('alert_triggered');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('reputation_scores');
    }
};