<?php

namespace App\Filament\Pages\Tenancy;

use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Models\WorkspaceMembership;
use App\Services\Auth\ManagedEnvironmentAccessScopeResolver;
use App\Services\Auth\ManagedEnvironmentMembershipManager;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Forms;
use Filament\Pages\Tenancy\RegisterTenant as BaseRegisterTenant;
use Filament\Schemas\Schema;
use Illuminate\Database\Eloquent\Model;

class RegisterTenant extends BaseRegisterTenant
{
    public static function getLabel(): string
    {
        return 'Register tenant';
    }

    /**
     * @return class-string<Model>
     */
    public function getModel(): string
    {
        return ManagedEnvironment::class;
    }

    public static function canView(): bool
    {
        $user = auth()->user();

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

        $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId();

        if ($workspaceId !== null) {
            $canRegisterInWorkspace = WorkspaceMembership::query()
                ->where('workspace_id', $workspaceId)
                ->where('user_id', $user->getKey())
                ->whereIn('role', ['owner', 'manager'])
                ->exists();

            if ($canRegisterInWorkspace) {
                return true;
            }
        }

        return false;
    }

    public function form(Schema $schema): Schema
    {
        return $schema
            ->schema([
                Forms\Components\TextInput::make('name')
                    ->required()
                    ->maxLength(255),
                Forms\Components\Select::make('environment')
                    ->options([
                        'prod' => 'PROD',
                        'dev' => 'DEV',
                        'staging' => 'STAGING',
                        'other' => 'Other',
                    ])
                    ->default('other')
                    ->required(),
                Forms\Components\TextInput::make('managed_environment_id')
                    ->label('ManagedEnvironment ID (GUID)')
                    ->required()
                    ->maxLength(255)
                    ->unique(ignoreRecord: true),
                Forms\Components\TextInput::make('domain')
                    ->label('Primary domain')
                    ->maxLength(255)
                    ->helperText('Credentials are managed after tenant creation in Provider connections.'),
            ]);
    }

    /**
     * @param  array<string, mixed>  $data
     */
    protected function handleRegistration(array $data): Model
    {
        if (! static::canView()) {
            abort(403);
        }

        $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId();

        if ($workspaceId !== null) {
            $data['workspace_id'] = $workspaceId;
        }

        $tenant = ManagedEnvironment::create($data);

        $user = auth()->user();

        if ($user instanceof User && is_int($workspaceId)) {
            $explicitScopes = app(ManagedEnvironmentAccessScopeResolver::class)
                ->allowedManagedEnvironmentIdsForWorkspace($user, $workspaceId);

            if (is_array($explicitScopes)) {
                app(ManagedEnvironmentMembershipManager::class)->grantScope(
                    tenant: $tenant,
                    actor: $user,
                    member: $user,
                    source: 'manual',
                );
            }
        }

        return $tenant;
    }
}
