<?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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Only update stocks table (stock_ledgers already has account_id)
        Schema::table('stocks', function (Blueprint $table) {
            // Add new account_id column
            $table->unsignedBigInteger('account_id')->nullable()->after('item_id');
        });

        // Copy data from item_id to account_id
        DB::statement('UPDATE stocks SET account_id = item_id');

        // Drop old foreign key constraint from stocks table
        Schema::table('stocks', function (Blueprint $table) {
            $table->dropForeign(['item_id']);
        });

        // Drop old item_id column from stocks table
        Schema::table('stocks', function (Blueprint $table) {
            $table->dropColumn('item_id');
        });

        // Add new foreign key constraint for stocks table
        Schema::table('stocks', function (Blueprint $table) {
            $table->foreign('account_id')->references('id')->on('accounts')->restrictOnDelete();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Revert stocks table
        Schema::table('stocks', function (Blueprint $table) {
            // Add back item_id column
            $table->unsignedBigInteger('item_id')->nullable()->after('account_id');
        });

        // Copy data back from account_id to item_id
        DB::statement('UPDATE stocks SET item_id = account_id');

        // Drop new foreign key constraint
        Schema::table('stocks', function (Blueprint $table) {
            $table->dropForeign(['account_id']);
        });

        // Drop account_id column
        Schema::table('stocks', function (Blueprint $table) {
            $table->dropColumn('account_id');
        });

        // Add original foreign key constraint
        Schema::table('stocks', function (Blueprint $table) {
            $table->foreign('item_id')->references('id')->on('items')->restrictOnDelete();
        });
    }
};
