<?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::table('generated_reports', function (Blueprint $table) {
            if (! Schema::hasColumn('generated_reports', 'ai_status')) {
                $table->string('ai_status')->default('pending')->after('summary');
            }
            if (! Schema::hasColumn('generated_reports', 'ai_provider')) {
                $table->string('ai_provider')->nullable()->after('ai_status');
            }
            if (! Schema::hasColumn('generated_reports', 'ai_executive_summary')) {
                $table->longText('ai_executive_summary')->nullable()->after('ai_provider');
            }
            if (! Schema::hasColumn('generated_reports', 'ai_customer_note')) {
                $table->longText('ai_customer_note')->nullable()->after('ai_executive_summary');
            }
            if (! Schema::hasColumn('generated_reports', 'ai_technical_note')) {
                $table->longText('ai_technical_note')->nullable()->after('ai_customer_note');
            }
            if (! Schema::hasColumn('generated_reports', 'ai_risks')) {
                $table->json('ai_risks')->nullable()->after('ai_technical_note');
            }
            if (! Schema::hasColumn('generated_reports', 'ai_opportunities')) {
                $table->json('ai_opportunities')->nullable()->after('ai_risks');
            }
            if (! Schema::hasColumn('generated_reports', 'ai_actions')) {
                $table->json('ai_actions')->nullable()->after('ai_opportunities');
            }
            if (! Schema::hasColumn('generated_reports', 'ai_raw_response')) {
                $table->longText('ai_raw_response')->nullable()->after('ai_actions');
            }
            if (! Schema::hasColumn('generated_reports', 'ai_error_message')) {
                $table->text('ai_error_message')->nullable()->after('ai_raw_response');
            }
            if (! Schema::hasColumn('generated_reports', 'ai_generated_at')) {
                $table->timestamp('ai_generated_at')->nullable()->after('ai_error_message');
            }
        });
    }

    public function down(): void
    {
        Schema::table('generated_reports', function (Blueprint $table) {
            foreach ([
                'ai_status', 'ai_provider', 'ai_executive_summary', 'ai_customer_note', 'ai_technical_note',
                'ai_risks', 'ai_opportunities', 'ai_actions', 'ai_raw_response', 'ai_error_message', 'ai_generated_at',
            ] as $column) {
                if (Schema::hasColumn('generated_reports', $column)) {
                    $table->dropColumn($column);
                }
            }
        });
    }
};
