<?php

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

/**
 * Test Instances (Master Control): turns `tenants` into the unified "environment"
 * table for both live tenants and their isolated test copies.
 *
 *  - `environment`      (live|test) separates the two from a single table so the
 *                       tenant application, scope resolution and subdomain routing
 *                       are shared verbatim — a test instance is a full tenant row
 *                       with its own tenant_id-scoped data.
 *  - `parent_tenant_id` the live tenant a test instance mirrors (null on live rows).
 *  - `last_synced_at` / `last_synced_by`  stamp every "Sync from Live" run so
 *                       administrators can see how stale a test environment is and
 *                       who refreshed it (user's "Last Synced From Live" feature).
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('tenants', function (Blueprint $table): void {
            $table->string('environment', 10)
                ->default('live')
                ->after('status');
            $table->unsignedBigInteger('parent_tenant_id')
                ->nullable()
                ->after('environment')
                ->index();
            $table->timestamp('last_synced_at')
                ->nullable()
                ->after('parent_tenant_id');
            $table->unsignedBigInteger('last_synced_by')
                ->nullable()
                ->after('last_synced_at');
        });
    }

    public function down(): void
    {
        Schema::table('tenants', function (Blueprint $table): void {
            $table->dropColumn(['environment', 'parent_tenant_id', 'last_synced_at', 'last_synced_by']);
        });
    }
};