<?php

use App\Models\LegalDocument;
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
    {
        if (! Schema::hasTable('legal_documents')) {
            Schema::create('legal_documents', function (Blueprint $table) {
                $table->id();
                $table->string('key')->unique();
                $table->string('title');
                $table->longText('body')->nullable();
                $table->timestamps();
            });
        }

        foreach (LegalDocument::defaults() as $key => $document) {
            if (DB::table('legal_documents')->where('key', $key)->exists()) {
                continue;
            }

            DB::table('legal_documents')->insert([
                'key' => $key,
                'title' => $document['title'],
                'body' => $document['body'],
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }

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