<?php

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

return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('user_profiles')) {
            return;
        }

        // Add new columns if missing
        Schema::table('user_profiles', function (Blueprint $table) {
            if (! Schema::hasColumn('user_profiles', 'about')) {
                $table->text('about')->nullable()->after('bio');
            }
            if (! Schema::hasColumn('user_profiles', 'signature')) {
                $table->text('signature')->nullable()->after('about');
            }
            if (! Schema::hasColumn('user_profiles', 'description')) {
                $table->text('description')->nullable()->after('signature');
            }
        });

        // Copy existing `bio` data into `about` (safe no-op if bio missing)
        try {
            if (Schema::hasColumn('user_profiles', 'bio') && Schema::hasColumn('user_profiles', 'about')) {
                DB::statement('UPDATE `user_profiles` SET `about` = `bio` WHERE `about` IS NULL OR `about` = ""');
            }
        } catch (\Throwable $e) {
            // ignore copy errors
        }
    }

    public function down(): void
    {
        if (! Schema::hasTable('user_profiles')) {
            return;
        }

        Schema::table('user_profiles', function (Blueprint $table) {
            if (Schema::hasColumn('user_profiles', 'description')) {
                $table->dropColumn('description');
            }
            if (Schema::hasColumn('user_profiles', 'signature')) {
                $table->dropColumn('signature');
            }
            // keep `about` on down migration to avoid data loss; do not drop it automatically
        });
    }
};
