<?php

namespace App\Filament\Resources\Workspaces\Pages;

use App\Filament\Resources\Workspaces\WorkspaceResource;
use App\Models\User;
use App\Models\WorkspaceMembership;
use App\Services\Audit\WorkspaceAuditLogger;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Resources\Pages\CreateRecord;

class CreateWorkspace extends CreateRecord
{
    protected static string $resource = WorkspaceResource::class;

    protected function afterCreate(): void
    {
        $user = auth()->user();

        if (! $user instanceof User) {
            return;
        }

        WorkspaceMembership::query()->firstOrCreate(
            [
                'workspace_id' => $this->record->getKey(),
                'user_id' => $user->getKey(),
            ],
            [
                'role' => 'owner',
            ],
        );

        app(WorkspaceAuditLogger::class)->log(
            workspace: $this->record,
            action: 'workspace.created',
            actor: $user,
            resourceType: 'workspace',
            resourceId: (string) $this->record->getKey(),
            context: [
                'metadata' => [
                    'workspace_id' => (int) $this->record->getKey(),
                    'slug' => (string) $this->record->slug,
                ],
            ],
        );

        app(WorkspaceContext::class)->setCurrentWorkspace($this->record, $user, request());
    }
}
