<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * Creates a denormalized data pool table that contains the result of:
     * SELECT * FROM backend.transactions t
     * LEFT JOIN backend.transaction_outputs tout ON t.id = tout.transaction_id
     * WHERE t.status = 'done'
     */
    public function up(): void
    {
        Schema::create('backend_data_pool', function (Blueprint $table) {
            $table->id();

            // ===================================
            // FROM backend.transactions (t.*)
            // ===================================
            $table->integer('transaction_id')->index();
            $table->text('corporate_entity');
            $table->text('corporate_counterparty');
            $table->text('tx_date');
            $table->double('tx_amount');
            $table->text('tx_currency')->nullable();
            $table->text('tx_purpose')->nullable();
            $table->text('tx_country_outgoing')->nullable();
            $table->text('tx_country_incoming')->nullable();
            $table->text('source_file')->nullable();
            $table->text('raw_payload')->nullable();
            $table->text('status')->index();
            $table->text('created_at');
            $table->text('last_modified_at');

            // ===================================
            // FROM backend.transaction_outputs (tout.*)
            // ===================================
            $table->integer('prompt_id');
            $table->text('output_key')->index();
            $table->text('content');
            $table->integer('run_id')->nullable();

            // ===================================
            // Metadata for tracking sync
            // ===================================
            $table->timestamp('synced_at')->useCurrent();
            $table->timestamp('updated_at')->nullable();

            // ===================================
            // Composite Indexes for Performance
            // ===================================
            $table->index(['transaction_id', 'output_key']);
            $table->index(['transaction_id', 'prompt_id']);
            $table->index('synced_at');
        });
    }

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