<?php

use Hyperf\Database\Schema\Schema;
use Hyperf\Database\Schema\Blueprint;
use Hyperf\Database\Migrations\Migration;

class CreateChapterMembersTable extends Migration
{
    public function up(): void
    {
        Schema::create('chapter_members', function (Blueprint $table) {
            $table->id();
            $table->string('hashkey')->unique();
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('chapter_id');
            $table->string('position')->nullable()->comment('Position title from chapter_positions system setting');
            $table->boolean('is_manual_override')->default(false)->comment('True if manually assigned, overriding address-based auto-assignment');
            $table->boolean('is_active')->default(true);
            $table->unsignedBigInteger('assigned_by')->nullable();
            $table->timestamp('assigned_at')->nullable();
            $table->unsignedBigInteger('created_by')->nullable();
            $table->unsignedBigInteger('updated_by')->nullable();
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->cascadeOnDelete();
            $table->foreign('chapter_id')->references('id')->on('chapters')->cascadeOnDelete();
            $table->unique(['user_id', 'chapter_id']);
            $table->index(['chapter_id', 'is_active']);
            $table->index('user_id');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('chapter_members');
    }
}
