<?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::create('notifications', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->string('type');
            $table->morphs('notifiable');
            $table->text('data');
            $table->timestamp('read_at')->nullable();
            $table->timestamps();
        });

        Schema::create('loan_disbursements', function (Blueprint $table): void {
            $table->id();
            $table->string('disbursement_number')->unique();
            $table->foreignId('loan_id')->unique()->constrained()->restrictOnDelete();
            $table->foreignId('branch_id')->constrained()->restrictOnDelete();
            $table->foreignId('financial_account_id')->constrained('financial_accounts')->restrictOnDelete();
            $table->decimal('amount', 18, 2);
            $table->date('disbursement_date');
            $table->string('reference')->nullable();
            $table->text('notes')->nullable();
            $table->foreignId('disbursed_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('financial_account_transaction_id')->nullable()->unique()->constrained('financial_account_transactions')->restrictOnDelete();
            $table->timestamps();

            $table->index(['branch_id', 'disbursement_date']);
            $table->index(['financial_account_id', 'disbursement_date']);
        });

        Schema::table('loans', function (Blueprint $table): void {
            $table->timestamp('disbursed_at')->nullable()->after('approved_by');
            $table->foreignId('disbursed_by')->nullable()->after('disbursed_at')->constrained('users')->nullOnDelete();
            $table->timestamp('activated_at')->nullable()->after('disbursed_by');
            $table->timestamp('schedule_activated_at')->nullable()->after('activated_at');
        });
    }

    public function down(): void
    {
        Schema::table('loans', function (Blueprint $table): void {
            $table->dropConstrainedForeignId('disbursed_by');
            $table->dropColumn(['disbursed_at', 'activated_at', 'schedule_activated_at']);
        });

        Schema::dropIfExists('loan_disbursements');
        Schema::dropIfExists('notifications');
    }
};
