<?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('financial_reports', function (Blueprint $table) {
            $table->id();
            $table->foreignId('campaign_id')->nullable()->constrained()->onDelete('cascade');
            $table->foreignId('brand_id')->constrained('users')->onDelete('cascade');
            
            // Report Type: 'campaign' or 'brand_consolidated'
            $table->enum('report_type', ['campaign', 'brand_consolidated'])->default('campaign');
            
            // Financial Metrics
            $table->decimal('total_spend', 15, 2)->default(0);
            $table->decimal('total_revenue', 15, 2)->default(0);
            $table->decimal('net_profit', 15, 2)->default(0);
            $table->decimal('roi_percentage', 10, 2)->nullable();
            $table->integer('breakeven_days')->nullable();
            
            // Performance Metrics
            $table->bigInteger('total_clicks')->default(0);
            $table->bigInteger('total_impressions')->default(0);
            $table->bigInteger('total_conversions')->default(0);
            $table->decimal('avg_conversion_rate', 10, 2)->nullable();
            $table->decimal('avg_cost_per_conversion', 10, 2)->nullable();
            
            // AI Analysis Results
            $table->text('recommendations_text')->nullable();
            $table->json('actionable_insights')->nullable(); // Array of insights
            $table->json('spend_breakdown')->nullable();
            $table->json('revenue_breakdown')->nullable();
            $table->json('trend_analysis')->nullable();
            
            // Report Period
            $table->date('period_start');
            $table->date('period_end');
            
            // AI Processing
            $table->enum('ai_status', ['pending', 'processing', 'completed', 'failed'])->default('pending');
            $table->timestamp('ai_processed_at')->nullable();
            $table->text('ai_error')->nullable();
            
            // Export tracking
            $table->integer('export_count')->default(0);
            $table->timestamp('last_exported_at')->nullable();
            
            $table->timestamps();
            $table->softDeletes();
            
            // Indexes
            $table->index(['brand_id', 'report_type', 'period_start']);
            $table->index(['campaign_id', 'period_start']);
            $table->index('ai_status');
        });
    }

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