<?php

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

return new class extends Migration
{
    /**
     * Tables that receive a straight organization_id column + index.
     * Keyed by table name => column position hint (placed after 'id').
     */
    private array $tables = [
        'users',
        'categories',
        'products',
        'suppliers',
        'purchases',
        'purchase_items',
        'customers',
        'sales',
        'sale_items',
        'payments',
        'returns',
        'return_items',
        'inventory_adjustments',
        'expenses',
        'settings',
        'system_logs',
        'loyalty_transactions',
    ];

    public function up(): void
    {
        // Add organization_id to all standard tenant tables
        foreach ($this->tables as $tableName) {
            Schema::table($tableName, function (Blueprint $table) {
                $table->unsignedBigInteger('organization_id')->nullable()->after('id');
                $table->index('organization_id');
            });
        }

        // expense_categories: drop existing unique-name constraint, add composite
        Schema::table('expense_categories', function (Blueprint $table) {
            $table->unsignedBigInteger('organization_id')->nullable()->after('id');
            $table->dropUnique('expense_categories_name_unique');
            $table->unique(['organization_id', 'name'], 'expense_categories_org_name_unique');
            $table->index('organization_id', 'expense_categories_org_id_index');
        });
    }

    public function down(): void
    {
        // Restore expense_categories unique constraint on name
        Schema::table('expense_categories', function (Blueprint $table) {
            $table->dropIndex('expense_categories_org_id_index');
            $table->dropUnique('expense_categories_org_name_unique');
            $table->dropColumn('organization_id');
            $table->unique('name');
        });

        foreach (array_reverse($this->tables) as $tableName) {
            Schema::table($tableName, function (Blueprint $table) {
                $table->dropIndex(['organization_id']);
                $table->dropColumn('organization_id');
            });
        }
    }
};
