<?php

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

class UpdateUserProfilesAvatars extends Migration
{
    /**
     * Run the migrations.
     *
     * Adds avatar metadata fields and renames legacy column if present.
     *
     * @return void
     */
    public function up()
    {
        if (!Schema::hasTable('user_profiles')) {
            return;
        }

        Schema::table('user_profiles', function (Blueprint $table) {
            if (!Schema::hasColumn('user_profiles', 'avatar_hash')) {
                $table->char('avatar_hash', 40)->nullable();
            }
            if (!Schema::hasColumn('user_profiles', 'avatar_updated_at')) {
                $table->dateTime('avatar_updated_at')->nullable();
            }
            if (!Schema::hasColumn('user_profiles', 'avatar_mime')) {
                $table->string('avatar_mime', 50)->nullable();
            }
        });

        // Attempt to rename legacy `avatar` column to `avatar_legacy` if it exists
        if (Schema::hasColumn('user_profiles', 'avatar') && !Schema::hasColumn('user_profiles', 'avatar_legacy')) {
            // Use DB statement to avoid requiring doctrine/dbal at runtime
            try {
                DB::statement('ALTER TABLE user_profiles CHANGE COLUMN `avatar` `avatar_legacy` VARCHAR(255) NULL');
            } catch (\Exception $e) {
                // If the rename fails, we'll leave the legacy column as-is; migrations shouldn't break.
            }
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        if (!Schema::hasTable('user_profiles')) {
            return;
        }

        Schema::table('user_profiles', function (Blueprint $table) {
            if (Schema::hasColumn('user_profiles', 'avatar_hash')) {
                $table->dropColumn('avatar_hash');
            }
            if (Schema::hasColumn('user_profiles', 'avatar_updated_at')) {
                $table->dropColumn('avatar_updated_at');
            }
            if (Schema::hasColumn('user_profiles', 'avatar_mime')) {
                $table->dropColumn('avatar_mime');
            }
        });

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