<?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
{
    /**
     * The tables that need tenant_id.
     * We add as NULLABLE with default=1 so existing rows get assigned to the
     * default tenant without errors. After backfill we leave it nullable so
     * the foreign key is soft (SQLite doesn't enforce FKs by default anyway).
     */
    protected array $tables = [
        'users',
        'branches',
        'categories',
        'products',
        'option_sets',
        'inner_option_sets',
        'ingredients',
        'recipes',
        'orders',
        'expenses',
        'expense_categories',
        'cash_registers',
        'production_batches',
        'stock_ledgers',
        'purchase_orders',
    ];

    public function up(): void
    {
        // ── Step 1: Add nullable tenant_id with default 1 to each table ──────
        foreach ($this->tables as $table) {
            if (!Schema::hasColumn($table, 'tenant_id')) {
                Schema::table($table, function (Blueprint $blueprint) {
                    $blueprint->unsignedBigInteger('tenant_id')->nullable()->default(1)->after('id');
                });
            }
        }

        // ── Step 2: Backfill – assign all existing rows to tenant_id = 1 ─────
        // (Default tenant is created by DefaultTenantSeeder before migration runs,
        //  or seeded right after. Safe to do here too.)
        foreach ($this->tables as $table) {
            DB::table($table)->whereNull('tenant_id')->update(['tenant_id' => 1]);
        }
    }

    public function down(): void
    {
        foreach ($this->tables as $table) {
            if (Schema::hasColumn($table, 'tenant_id')) {
                Schema::table($table, function (Blueprint $blueprint) {
                    $blueprint->dropColumn('tenant_id');
                });
            }
        }
    }
};
