<?php

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

class CreateMsgraphPendingChangesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('msgraph_pending_changes', function (Blueprint $table) {
            $table->id();

            // Polymorphic relationship to the model (Committee or WorkGroup)
            $table->morphs('model'); // creates model_type and model_id columns

            // Action type: user_joined, user_left, user_type_changed, user_deleted, user_state_changed
            $table->enum('action', ['user_joined', 'user_left', 'user_type_changed', 'user_deleted', 'user_state_changed']);

            // User involved in the change
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

            // Membership details
            $table->string('old_membership_type', 10)->nullable(); // previous type (for type changes and leaves)
            $table->string('new_membership_type', 10)->nullable(); // new type (for joins and type changes)

            // Additional metadata as JSON
            $table->json('metadata')->nullable();

            // Processing status
            $table->boolean('processed')->default(false);
            $table->timestamp('processed_at')->nullable();

            // Priority for processing order
            $table->enum('priority', ['low', 'normal', 'high'])->default('normal');

            $table->timestamps();

            // Indexes for better performance
            $table->index(['processed', 'priority', 'created_at']);
            $table->index(['user_id', 'created_at']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('msgraph_pending_changes');
    }
}
