<?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 {
    public function up(): void
    {
        if (!Schema::hasTable('user_profiles')) {
            return;
        }

        if (Schema::hasColumn('user_profiles', 'avatar') && !Schema::hasColumn('user_profiles', 'avatar_legacy')) {
            try {
                DB::statement('ALTER TABLE `user_profiles` CHANGE COLUMN `avatar` `avatar_legacy` VARCHAR(255) NULL');
            } catch (\Throwable $e) {
            }
        }

        Schema::table('user_profiles', function (Blueprint $table) {
            if (!Schema::hasColumn('user_profiles', 'avatar_legacy')) {
                $table->string('avatar_legacy', 255)->nullable();
            }

            if (!Schema::hasColumn('user_profiles', 'avatar_hash')) {
                $table->char('avatar_hash', 64)->nullable()->index();
            }

            if (!Schema::hasColumn('user_profiles', 'avatar_mime')) {
                $table->string('avatar_mime', 50)->nullable();
            }

            if (!Schema::hasColumn('user_profiles', 'avatar_updated_at')) {
                $table->dateTime('avatar_updated_at')->nullable();
            }
        });

        if (Schema::hasColumn('user_profiles', 'avatar_hash')) {
            try {
                DB::statement('ALTER TABLE `user_profiles` MODIFY COLUMN `avatar_hash` CHAR(64) NULL');
            } catch (\Throwable $e) {
            }
        }
    }

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

        if (Schema::hasColumn('user_profiles', 'avatar_hash')) {
            try {
                DB::statement('ALTER TABLE `user_profiles` MODIFY COLUMN `avatar_hash` CHAR(40) NULL');
            } catch (\Throwable $e) {
            }
        }
    }
};
