<?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
{
    public function up(): void
    {
        Schema::create('managed_environment_user', function (Blueprint $table) {
            $table->foreignId('managed_environment_id')->constrained()->cascadeOnDelete();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('role')->default('owner');
            $table->timestamps();

            $table->unique(['managed_environment_id', 'user_id']);
        });

        $now = now();

        $tenantIds = DB::table('managed_environments')
            ->whereNull('deleted_at')
            ->pluck('id');

        $userIds = DB::table('users')->pluck('id');

        if ($tenantIds->isEmpty() || $userIds->isEmpty()) {
            return;
        }

        $rows = [];

        foreach ($tenantIds as $tenantId) {
            foreach ($userIds as $userId) {
                $rows[] = [
                    'managed_environment_id' => $tenantId,
                    'user_id' => $userId,
                    'role' => 'owner',
                    'created_at' => $now,
                    'updated_at' => $now,
                ];

                if (count($rows) >= 500) {
                    DB::table('managed_environment_user')->insertOrIgnore($rows);
                    $rows = [];
                }
            }
        }

        if ($rows !== []) {
            DB::table('managed_environment_user')->insertOrIgnore($rows);
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('managed_environment_user');
    }
};
