<?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('assets')) {
            return;
        }

        Schema::table('assets', function (Blueprint $table) {
            if (! Schema::hasColumn('assets', 'notes')) {
                $table->text('notes')->nullable()->after('purchase_date');
            }
        });

        // Legacy schema used description; move data to notes when notes is empty.
        if (Schema::hasColumn('assets', 'description')) {
            $driver = Schema::getConnection()->getDriverName();
            if ($driver === 'mysql') {
                DB::statement(
                    'UPDATE `assets` SET `notes` = `description` WHERE (`notes` IS NULL OR `notes` = \'\') AND `description` IS NOT NULL'
                );
            } else {
                DB::table('assets')
                    ->where(function ($q) {
                        $q->whereNull('notes')->orWhere('notes', '');
                    })
                    ->whereNotNull('description')
                    ->update(['notes' => DB::raw('description')]);
            }
        }
    }

    public function down(): void
    {
        if (! Schema::hasTable('assets')) {
            return;
        }

        Schema::table('assets', function (Blueprint $table) {
            if (Schema::hasColumn('assets', 'notes')) {
                $table->dropColumn('notes');
            }
        });
    }
};
