<?php

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

return new class extends Migration
{
    /**
     * Add purchase_type to distinguish mandatory obligations from on-demand purchases.
     *
     * - 'assigned'  : Traditional obligations — admin assigns dues/levies/fines to members.
     *                  These appear on the Financial Obligations page and affect standing.
     * - 'on_demand' : Member-initiated purchases — library content, store items, event tickets, etc.
     *                  These do NOT appear as obligations. They're tracked in a separate "Purchases" view.
     */
    public function up(): void
    {
        Schema::table('financial_assignments', function (Blueprint $table) {
            $table->string('purchase_type', 20)->default('assigned')->after('status');
            $table->index('purchase_type');
        });

        // Backfill existing library purchases as 'on_demand'
        // Library purchases have a FinancialItem with related_type = LibraryItem class
        DB::statement("
            UPDATE financial_assignments
            SET purchase_type = 'on_demand'
            WHERE financial_item_id IN (
                SELECT id FROM financial_items
                WHERE related_type = 'App\\\\Models\\\\LibraryItem'
            )
        ");
    }

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