<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('financial_assignments', function (Blueprint $table) {
            // Billing Period Tracking
            $table->string('billing_period', 50)->nullable()->after('financial_item_id')
                ->comment('e.g., "2024-01", "2024-Q1", "2024" for tracking which period this covers');
            $table->date('period_start_date')->nullable()->after('billing_period')
                ->comment('Start of the billing period (e.g., 2024-01-01)');
            $table->date('period_end_date')->nullable()->after('period_start_date')
                ->comment('End of the billing period (e.g., 2024-01-31)');

            // Late Fee Tracking
            $table->decimal('late_fee_applied', 12, 2)->default(0)->after('amount_paid')
                ->comment('Late fee amount added to this assignment');
            $table->timestamp('late_fee_applied_at')->nullable()->after('late_fee_applied');

            // Generation Tracking
            $table->boolean('is_auto_generated')->default(false)->after('late_fee_applied_at')
                ->comment('Was this assignment created by automated recurring generation?');
            $table->timestamp('generated_at')->nullable()->after('is_auto_generated');
            $table->string('generation_batch_id', 100)->nullable()->after('generated_at')
                ->comment('UUID to group all assignments generated in same batch');

            // Add indexes for performance
            $table->index(['association_id', 'billing_period'], 'idx_assoc_billing_period');
            $table->index(['user_id', 'period_end_date'], 'idx_user_period_end');
            $table->index('generation_batch_id');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('financial_assignments', function (Blueprint $table) {
            $table->dropIndex('idx_assoc_billing_period');
            $table->dropIndex('idx_user_period_end');
            $table->dropIndex(['generation_batch_id']);

            $table->dropColumn([
                'billing_period',
                'period_start_date',
                'period_end_date',
                'late_fee_applied',
                'late_fee_applied_at',
                'is_auto_generated',
                'generated_at',
                'generation_batch_id',
            ]);
        });
    }
};
