<?php

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

/**
 * Ladill Meet core schema — multi-branch organizations.
 *
 * Hierarchy: owner_ref → Organization → Branch → Member
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('meet_organizations', function (Blueprint $table) {
            $table->id();
            $table->string('owner_ref')->index();
            $table->string('name');
            $table->string('slug')->index();
            $table->string('logo_path')->nullable();
            $table->string('timezone')->default('UTC');
            $table->json('settings')->nullable();
            $table->timestamps();
            $table->softDeletes();
            $table->unique(['owner_ref', 'slug']);
        });

        Schema::create('meet_branches', function (Blueprint $table) {
            $table->id();
            $table->string('owner_ref')->index();
            $table->foreignId('organization_id')->constrained('meet_organizations')->cascadeOnDelete();
            $table->string('name');
            $table->string('code')->nullable();
            $table->string('address')->nullable();
            $table->string('phone')->nullable();
            $table->boolean('is_active')->default(true);
            $table->timestamps();
            $table->softDeletes();
        });

        Schema::create('meet_members', function (Blueprint $table) {
            $table->id();
            $table->string('owner_ref')->index();
            $table->foreignId('organization_id')->constrained('meet_organizations')->cascadeOnDelete();
            $table->string('user_ref')->index();
            $table->string('role');
            $table->foreignId('branch_id')->nullable()->constrained('meet_branches')->nullOnDelete();
            $table->timestamps();
            $table->unique(['organization_id', 'user_ref']);
        });

        Schema::create('meet_audit_logs', function (Blueprint $table) {
            $table->id();
            $table->string('owner_ref')->index();
            $table->foreignId('organization_id')->nullable()->constrained('meet_organizations')->nullOnDelete();
            $table->string('actor_ref')->nullable();
            $table->string('action');
            $table->string('subject_type')->nullable();
            $table->unsignedBigInteger('subject_id')->nullable();
            $table->json('metadata')->nullable();
            $table->string('ip_address')->nullable();
            $table->timestamp('created_at')->useCurrent();
            $table->index(['owner_ref', 'created_at']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('meet_audit_logs');
        Schema::dropIfExists('meet_members');
        Schema::dropIfExists('meet_branches');
        Schema::dropIfExists('meet_organizations');
    }
};
