<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // 삭제된 레코드 메인 테이블
        Schema::create('archived_records', function (Blueprint $table) {
            $table->id();
            $table->enum('record_type', ['tenant', 'user'])->comment('레코드 타입');
            $table->unsignedBigInteger('original_id')->comment('원본 레코드 ID');
            $table->json('main_data')->comment('메인 테이블 데이터 (JSON)');
            $table->string('schema_version', 50)->default('v1.0')->comment('스키마 버전');
            $table->unsignedBigInteger('deleted_by')->nullable()->comment('삭제자 ID');
            $table->timestamp('deleted_at')->comment('삭제 일시');
            $table->text('notes')->nullable()->comment('삭제 사유/비고');
            $table->timestamps();

            $table->index(['record_type', 'original_id']);
            $table->index('deleted_at');
            $table->index('deleted_by');
        });

        // 삭제된 레코드의 관련 테이블 데이터
        Schema::create('archived_record_relations', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('archived_record_id')->comment('archived_records FK');
            $table->string('table_name', 100)->comment('테이블명');
            $table->json('data')->comment('해당 테이블의 모든 레코드 (JSON 배열)');
            $table->integer('record_count')->default(0)->comment('레코드 개수');
            $table->timestamps();

            $table->foreign('archived_record_id')
                ->references('id')
                ->on('archived_records')
                ->onDelete('cascade');

            $table->index(['archived_record_id', 'table_name']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('archived_record_relations');
        Schema::dropIfExists('archived_records');
    }
};
