<?php

namespace App\Domains\Workspace\Actions;

use App\Domains\Workspace\Models\Workspace;
use App\Domains\Workspace\Models\WorkspaceMember;
use App\Models\User;
use Illuminate\Support\Str;

class CreateWorkspace
{
    /** @param array<string, mixed> $data */
    public function handle(User $owner, array $data): Workspace
    {
        $workspace = Workspace::create([
            'name' => $data['name'],
            'slug' => $this->uniqueSlug(Str::slug($data['name'])),
            'owner_id' => $owner->id,
        ]);

        WorkspaceMember::create([
            'workspace_id' => $workspace->id,
            'user_id' => $owner->id,
            'role' => 'owner',
            'joined_at' => now(),
        ]);

        if (! $owner->default_workspace_id) {
            $owner->update(['default_workspace_id' => $workspace->id]);
        }

        return $workspace;
    }

    private function uniqueSlug(string $base): string
    {
        $slug = $base;
        $i = 2;
        while (Workspace::where('slug', $slug)->exists()) {
            $slug = "{$base}-{$i}";
            $i++;
        }

        return $slug;
    }
}
