<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        $tables = ['document_data', 'document_approvals', 'document_attachments'];

        foreach ($tables as $table) {
            Schema::table($table, function (Blueprint $table) {
                $table->unsignedBigInteger('tenant_id')->nullable()->after('id')->comment('테넌트 ID');
                $table->index('tenant_id');
            });

            // 부모 테이블(documents)에서 tenant_id 채우기
            DB::statement("
                UPDATE {$table} t
                JOIN documents d ON t.document_id = d.id
                SET t.tenant_id = d.tenant_id
            ");
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        $tables = ['document_data', 'document_approvals', 'document_attachments'];

        foreach ($tables as $table) {
            Schema::table($table, function (Blueprint $table) {
                $table->dropIndex(['tenant_id']);
                $table->dropColumn('tenant_id');
            });
        }
    }
};