<?php

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

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

        $now = now();

        $defaultWorkspaceId = DB::table('workspaces')
            ->where('slug', 'default')
            ->value('id');

        if (! $defaultWorkspaceId) {
            $defaultWorkspaceId = DB::table('workspaces')->insertGetId([
                'name' => 'Default Workspace',
                'slug' => 'default',
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        }

        if (Schema::hasTable('managed_environments') && Schema::hasColumn('managed_environments', 'workspace_id')) {
            DB::table('managed_environments')
                ->whereNull('workspace_id')
                ->update([
                    'workspace_id' => $defaultWorkspaceId,
                    'updated_at' => $now,
                ]);
        }

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

        $roleRankToRole = [
            4 => 'owner',
            3 => 'manager',
            2 => 'operator',
            1 => 'readonly',
        ];

        $userRoleRanks = collect();

        if (Schema::hasTable('managed_environment_memberships')) {
            $userRoleRanks = DB::table('managed_environment_memberships')
                ->select([
                    'user_id',
                    DB::raw("MAX(CASE role WHEN 'owner' THEN 4 WHEN 'manager' THEN 3 WHEN 'operator' THEN 2 WHEN 'readonly' THEN 1 ELSE 0 END) AS role_rank"),
                ])
                ->groupBy('user_id')
                ->get();
        }

        $rows = [];
        $userIds = [];

        foreach ($userRoleRanks as $row) {
            $role = $roleRankToRole[(int) $row->role_rank] ?? null;

            if (! $role) {
                continue;
            }

            $rows[] = [
                'workspace_id' => $defaultWorkspaceId,
                'user_id' => $row->user_id,
                'role' => $role,
                'created_at' => $now,
                'updated_at' => $now,
            ];
            $userIds[] = $row->user_id;
        }

        if (empty($rows) && Schema::hasTable('users')) {
            $firstUserId = DB::table('users')->orderBy('id')->value('id');

            if ($firstUserId) {
                $rows[] = [
                    'workspace_id' => $defaultWorkspaceId,
                    'user_id' => $firstUserId,
                    'role' => 'owner',
                    'created_at' => $now,
                    'updated_at' => $now,
                ];
                $userIds[] = $firstUserId;
            }
        }

        if (! empty($rows)) {
            foreach (array_chunk($rows, 500) as $chunk) {
                DB::table('workspace_memberships')->insertOrIgnore($chunk);
            }
        }

        $ownerCount = DB::table('workspace_memberships')
            ->where('workspace_id', $defaultWorkspaceId)
            ->where('role', 'owner')
            ->count();

        if ($ownerCount === 0) {
            $firstMembershipId = DB::table('workspace_memberships')
                ->where('workspace_id', $defaultWorkspaceId)
                ->orderBy('id')
                ->value('id');

            if ($firstMembershipId) {
                DB::table('workspace_memberships')
                    ->where('id', $firstMembershipId)
                    ->update([
                        'role' => 'owner',
                        'updated_at' => $now,
                    ]);
            }
        }

        if (Schema::hasTable('users') && ! empty($userIds) && Schema::hasColumn('users', 'last_workspace_id')) {
            DB::table('users')
                ->whereIn('id', array_unique($userIds))
                ->whereNull('last_workspace_id')
                ->update([
                    'last_workspace_id' => $defaultWorkspaceId,
                    'updated_at' => $now,
                ]);
        }
    }

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