<?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
    {
        if (Schema::hasTable('ai_tasks')) return;
        
        Schema::create('ai_tasks', function (Blueprint $table) {
            $table->id();
            $table->string('task_type');
            $table->string('status')->default('pending');
            $table->foreignId('user_id')->nullable()->constrained()->onDelete('set null');
            $table->morphs('taskable');
            $table->json('input_data')->nullable();
            $table->json('output_data')->nullable();
            $table->text('error_message')->nullable();
            $table->integer('tokens_used')->default(0);
            $table->decimal('cost', 10, 4)->default(0);
            $table->timestamp('started_at')->nullable();
            $table->timestamp('completed_at')->nullable();
            $table->timestamps();
            
            $table->index(['task_type', 'status']);
            $table->index('created_at');
        });

        Schema::create('ai_reports', function (Blueprint $table) {
            $table->id();
            $table->string('report_type');
            $table->string('period');
            $table->date('period_start');
            $table->date('period_end');
            $table->json('data');
            $table->json('insights')->nullable();
            $table->json('recommendations')->nullable();
            $table->boolean('is_reviewed')->default(false);
            $table->foreignId('reviewed_by')->nullable()->constrained('users')->onDelete('set null');
            $table->timestamps();
            
            $table->index(['report_type', 'period']);
        });
    }

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

