<?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
    {
        // First, drop all existing foreign key constraints that reference the items table
        $this->dropItemForeignKeys();

        // Then add new foreign key constraints that reference the accounts table
        $this->addAccountForeignKeys();
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Drop the new foreign key constraints
        $this->dropAccountForeignKeys();

        // Re-add the old foreign key constraints
        $this->addItemForeignKeys();
    }

    private function dropItemForeignKeys(): void
    {
        $tables = [
            'purchase_request_items' => 'purchase_request_items_item_id_foreign',
            'purchase_order_items' => 'purchase_order_items_item_id_foreign',
            'grn_items' => 'grn_items_item_id_foreign',
            'gate_pass_items' => 'gate_pass_items_item_id_foreign',
            'qc_items' => 'qc_items_item_id_foreign',
            'bom_items' => 'bom_items_item_id_foreign',
            'stock_transfer_items' => 'stock_transfer_items_item_id_foreign',
            'inventory_balances' => 'inventory_balances_item_id_foreign',
            'inventory_moves' => 'inventory_moves_item_id_foreign',
            'stock_balances' => 'stock_balances_item_id_foreign',
            'warehouse_current_stocks' => 'warehouse_current_stocks_item_id_foreign',
            'warehouse_stock_ledgers' => 'warehouse_stock_ledgers_item_id_foreign',
            'item_suppliers' => 'item_suppliers_item_id_foreign',
            'item_variations' => 'item_variations_item_id_foreign',
            'boms' => 'boms_item_id_foreign',
            'quality_checks' => 'quality_checks_item_id_foreign',
            'inspection_results' => 'inspection_results_item_id_foreign',
            'wo_material_issues' => 'wo_material_issues_item_id_foreign',
            'wo_receipts' => 'wo_receipts_item_id_foreign',
        ];

        foreach ($tables as $table => $constraint) {
            try {
                Schema::table($table, function (Blueprint $table) use ($constraint) {
                    $table->dropForeign($constraint);
                });
            } catch (Exception $e) {
                // Constraint might not exist, continue
                echo "Could not drop constraint {$constraint}: " . $e->getMessage() . "\n";
            }
        }
    }

    private function addAccountForeignKeys(): void
    {
        // Add foreign key constraints to accounts table
        $this->addForeignKey('purchase_request_items', 'item_id', 'accounts', 'id');
        $this->addForeignKey('purchase_order_items', 'item_id', 'accounts', 'id');
        $this->addForeignKey('grn_items', 'item_id', 'accounts', 'id');
        $this->addForeignKey('gate_pass_items', 'item_id', 'accounts', 'id');
        $this->addForeignKey('qc_items', 'item_id', 'accounts', 'id');
        $this->addForeignKey('bom_items', 'item_id', 'accounts', 'id');
        $this->addForeignKey('stock_transfer_items', 'item_id', 'accounts', 'id');
        $this->addForeignKey('inventory_balances', 'item_id', 'accounts', 'id');
        $this->addForeignKey('inventory_moves', 'item_id', 'accounts', 'id');
        $this->addForeignKey('stock_balances', 'item_id', 'accounts', 'id');
        $this->addForeignKey('warehouse_current_stocks', 'item_id', 'accounts', 'id');
        $this->addForeignKey('warehouse_stock_ledgers', 'item_id', 'accounts', 'id');
        $this->addForeignKey('item_suppliers', 'item_id', 'accounts', 'id');
        $this->addForeignKey('item_variations', 'item_id', 'accounts', 'id');
        $this->addForeignKey('boms', 'item_id', 'accounts', 'id');
        $this->addForeignKey('quality_checks', 'item_id', 'accounts', 'id');
        $this->addForeignKey('inspection_results', 'item_id', 'accounts', 'id');
        $this->addForeignKey('wo_material_issues', 'item_id', 'accounts', 'id');
        $this->addForeignKey('wo_receipts', 'item_id', 'accounts', 'id');
    }

    private function addForeignKey(string $table, string $column, string $referencedTable, string $referencedColumn): void
    {
        try {
            Schema::table($table, function (Blueprint $table) use ($column, $referencedTable, $referencedColumn) {
                $table->foreign($column)
                      ->references($referencedColumn)
                      ->on($referencedTable)
                      ->onDelete('restrict')
                      ->onUpdate('cascade');
            });
        } catch (Exception $e) {
            echo "Could not add foreign key for {$table}.{$column}: " . $e->getMessage() . "\n";
        }
    }

    private function dropAccountForeignKeys(): void
    {
        $tables = [
            'purchase_request_items',
            'purchase_order_items',
            'grn_items',
            'gate_pass_items',
            'qc_items',
            'bom_items',
            'stock_transfer_items',
            'inventory_balances',
            'inventory_moves',
            'stock_balances',
            'warehouse_current_stocks',
            'warehouse_stock_ledgers',
            'item_suppliers',
            'item_variations',
            'boms',
            'quality_checks',
            'inspection_results',
            'wo_material_issues',
            'wo_receipts',
        ];

        foreach ($tables as $table) {
            try {
                Schema::table($table, function (Blueprint $table) {
                    $table->dropForeign([$table . '_item_id_foreign']);
                });
            } catch (Exception $e) {
                // Constraint might not exist, continue
                echo "Could not drop foreign key for {$table}: " . $e->getMessage() . "\n";
            }
        }
    }

    private function addItemForeignKeys(): void
    {
        // Re-add the old foreign key constraints (for rollback)
        $this->addForeignKey('purchase_request_items', 'item_id', 'items', 'id');
        $this->addForeignKey('purchase_order_items', 'item_id', 'items', 'id');
        $this->addForeignKey('grn_items', 'item_id', 'items', 'id');
        $this->addForeignKey('gate_pass_items', 'item_id', 'items', 'id');
        $this->addForeignKey('qc_items', 'item_id', 'items', 'id');
        $this->addForeignKey('bom_items', 'item_id', 'items', 'id');
        $this->addForeignKey('stock_transfer_items', 'item_id', 'items', 'id');
        $this->addForeignKey('inventory_balances', 'item_id', 'items', 'id');
        $this->addForeignKey('inventory_moves', 'item_id', 'items', 'id');
        $this->addForeignKey('stock_balances', 'item_id', 'items', 'id');
        $this->addForeignKey('warehouse_current_stocks', 'item_id', 'items', 'id');
        $this->addForeignKey('warehouse_stock_ledgers', 'item_id', 'items', 'id');
        $this->addForeignKey('item_suppliers', 'item_id', 'items', 'id');
        $this->addForeignKey('item_variations', 'item_id', 'items', 'id');
        $this->addForeignKey('boms', 'item_id', 'items', 'id');
        $this->addForeignKey('quality_checks', 'item_id', 'items', 'id');
        $this->addForeignKey('inspection_results', 'item_id', 'items', 'id');
        $this->addForeignKey('wo_material_issues', 'item_id', 'items', 'id');
        $this->addForeignKey('wo_receipts', 'item_id', 'items', 'id');
    }
};
