<?php

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

class HardenFinanceSyncWebhooks extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('finance_webhook_events')) {
            Schema::create('finance_webhook_events', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('event_id')->unique();
                $table->string('transaction_id')->nullable()->unique('finance_webhook_events_transaction_unique');
                $table->string('admission_number', 50)->index();
                $table->unsignedBigInteger('invoice_id')->nullable();
                $table->decimal('amount', 15, 2)->nullable();
                $table->string('status', 50)->nullable();
                $table->json('payload')->nullable();
                $table->timestamp('received_at')->nullable();
                $table->timestamps();
            });
        }

        if (!Schema::hasTable('finance_sync_cache')) {
            Schema::create('finance_sync_cache', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->unsignedInteger('school_id')->nullable();
                $table->string('admission_number', 50);
                $table->json('summary')->nullable();
                $table->json('invoices')->nullable();
                $table->string('source', 40)->default('wordpress');
                $table->timestamp('fetched_at')->nullable();
                $table->timestamp('expires_at')->nullable();
                $table->timestamps();

                $table->unique(['school_id', 'admission_number'], 'finance_sync_cache_school_admission_unique');
            });
        }
    }

    public function down()
    {
        Schema::dropIfExists('finance_sync_cache');
        Schema::dropIfExists('finance_webhook_events');
    }
}
