<?php

namespace App\Services;

use App\Enums\AppRole;
use App\Models\User;
use App\Models\UserRole;
use App\Models\Workspace;
use App\Models\WorkspaceMember;
use Illuminate\Support\Facades\DB;

class WorkspaceBootstrapService
{
    public function bootstrap(User $user, string $defaultName = 'My Collabs'): Workspace
    {
        return DB::transaction(function () use ($user, $defaultName) {
            $existingWs = WorkspaceMember::query()
                ->where('user_id', $user->id)
                ->orderBy('created_at')
                ->value('workspace_id');

            if ($existingWs !== null) {
                return Workspace::query()->findOrFail($existingWs);
            }

            $orphanId = Workspace::query()
                ->where('owner_id', $user->id)
                ->whereNotExists(function ($q) {
                    $q->select(DB::raw(1))
                        ->from('workspace_members')
                        ->whereColumn('workspace_members.workspace_id', 'workspaces.id');
                })
                ->orderBy('created_at')
                ->value('id');

            if ($orphanId !== null) {
                WorkspaceMember::query()->firstOrCreate(
                    [
                        'workspace_id' => $orphanId,
                        'user_id' => $user->id,
                    ],
                    ['role' => AppRole::Influencer->value]
                );
                UserRole::query()->firstOrCreate(
                    [
                        'user_id' => $user->id,
                        'role' => AppRole::Influencer->value,
                    ]
                );

                return Workspace::query()->findOrFail($orphanId);
            }

            $workspace = Workspace::query()->create([
                'name' => $defaultName,
                'owner_id' => $user->id,
            ]);

            WorkspaceMember::query()->create([
                'workspace_id' => $workspace->id,
                'user_id' => $user->id,
                'role' => AppRole::Influencer->value,
            ]);

            UserRole::query()->firstOrCreate(
                [
                    'user_id' => $user->id,
                    'role' => AppRole::Influencer->value,
                ]
            );

            return $workspace;
        });
    }
}
