<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('transactions', function (Blueprint $table) {
            $table->dropForeign(['from_account_id']);
            $table->dropForeign(['to_account_id']);
            $table->dropColumn(['from_account_id', 'to_account_id']);
        });

        Schema::dropIfExists('accounts');
    }

    public function down(): void
    {
        Schema::create('accounts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
            $table->enum('type', ['BANK', 'CASH', 'POS', 'CHEQUE', 'OTHER'])->default('BANK');
            $table->string('title');
            $table->string('identifier')->nullable();
            $table->string('bank_name')->nullable();
            $table->text('notes')->nullable();
            $table->boolean('is_active')->default(true)->index();
            $table->timestamp('voided_at')->nullable();
            $table->foreignId('voided_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
            $table->softDeletes();
            $table->index(['user_id', 'is_active']);
        });

        Schema::table('transactions', function (Blueprint $table) {
            $table->foreignId('from_account_id')->nullable()->after('to_user_id')->constrained('accounts')->nullOnDelete();
            $table->foreignId('to_account_id')->nullable()->after('from_account_id')->constrained('accounts')->nullOnDelete();
        });
    }
};
