<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        if (! Schema::hasTable('managed_environment_user')) {
            return;
        }

        if (! Schema::hasTable('managed_environment_memberships')) {
            return;
        }

        if (DB::table('managed_environment_memberships')->exists()) {
            return;
        }

        $now = now();
        $rows = [];

        foreach (DB::table('managed_environment_user')->select(['managed_environment_id', 'user_id', 'role'])->cursor() as $pivot) {
            $rows[] = [
                'id' => (string) Str::uuid(),
                'managed_environment_id' => (int) $pivot->managed_environment_id,
                'user_id' => (int) $pivot->user_id,
                'role' => is_string($pivot->role) && $pivot->role !== '' ? $pivot->role : 'owner',
                'source' => 'manual',
                'source_ref' => null,
                'created_by_user_id' => null,
                'created_at' => $now,
                'updated_at' => $now,
            ];

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

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

    /**
     * Reverse the migrations.
     */
    public function down(): void {}
};
