<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    /**
     * Backfill NULL due_date values on existing financial assignments.
     *
     * New assignments will never have NULL due_date thanks to the
     * model boot() hook added alongside this migration. This fixes
     * historical records using the agreed-upon rules:
     *
     *   1. Recurring assignments (have period_end_date) → end of billing period
     *      Gives the member the full cycle to pay, e.g. "Feb 2026" → Feb 28.
     *   2. Everything else → created_at date (due immediately when assigned).
     */
    public function up(): void
    {
        // Step 1: Recurring assignments — use their billing period end date
        DB::table('financial_assignments')
            ->whereNull('due_date')
            ->whereNotNull('period_end_date')
            ->update(['due_date' => DB::raw('period_end_date')]);

        // Step 2: Non-recurring / no period — use date of creation
        DB::table('financial_assignments')
            ->whereNull('due_date')
            ->update(['due_date' => DB::raw('DATE(created_at)')]);
    }

    /**
     * Intentional no-op. Backfilled due_dates are a data improvement;
     * rolling back would reintroduce the NULL problem that breaks the
     * "Next Due" card, late fee engine, and overdue detection.
     * If needed, restore from backup.
     */
    public function down(): void
    {
        // No-op — see docblock above.
    }
};
