<?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('fixed_assets') && ! Schema::hasColumn('fixed_assets', 'current_book_value')) {
            Schema::table('fixed_assets', function (Blueprint $table) {
                $table->decimal('current_book_value', 15, 2)
                    ->default(0)
                    ->after('salvage_value');
            });

            DB::table('fixed_assets')->update([
                'current_book_value' => DB::raw('COALESCE(purchase_price, 0)'),
            ]);
        }
    }

    public function down(): void
    {
        if (Schema::hasTable('fixed_assets') && Schema::hasColumn('fixed_assets', 'current_book_value')) {
            Schema::table('fixed_assets', function (Blueprint $table) {
                $table->dropColumn('current_book_value');
            });
        }
    }
};
