<?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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('purchases', function (Blueprint $table) {
            // Drop old foreign key constraint if exists
            $table->dropForeign(['supplier_id']);

            // Add new fields
            $table->foreignId('bank_account_id')->nullable()->after('payment_method')->constrained('bank_accounts')->onDelete('set null');
            $table->enum('signature_type', ['manual', 'esignature'])->nullable()->after('terms')->default('manual');
            $table->foreignId('signature_id')->nullable()->after('signature_type')->constrained('signatures')->onDelete('set null');
        });

        // Point supplier_id at suppliers (MySQL may need FK checks off; SQLite tests skip raw ALTER)
        Schema::table('purchases', function (Blueprint $table) {
            $driver = Schema::getConnection()->getDriverName();

            if ($driver === 'mysql') {
                DB::statement('SET FOREIGN_KEY_CHECKS=0');
                try {
                    DB::statement('ALTER TABLE purchases DROP FOREIGN KEY purchases_supplier_id_foreign');
                } catch (\Throwable) {
                    // Name may differ or already dropped in prior Schema::table block
                }
            }

            $table->foreign('supplier_id')->references('id')->on('suppliers')->onDelete('set null');

            if ($driver === 'mysql') {
                DB::statement('SET FOREIGN_KEY_CHECKS=1');
            }
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('purchases', function (Blueprint $table) {
            $table->dropForeign(['bank_account_id']);
            $table->dropForeign(['signature_id']);
            $table->dropColumn(['bank_account_id', 'signature_type', 'signature_id']);

            // Revert supplier_id foreign key to customers
            $table->dropForeign(['supplier_id']);
            $table->foreign('supplier_id')->references('id')->on('customers')->onDelete('set null');
        });
    }
};
