<?php

declare(strict_types=1);

namespace App\Support\Navigation;

use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

final readonly class WorkspaceHubEnvironmentFilter
{
    private function __construct(
        private ManagedEnvironment $environment,
    ) {}

    public static function fromRequest(Request $request, Workspace $workspace): ?self
    {
        if (! $request->query->has('environment_id')) {
            return null;
        }

        $environmentId = $request->query('environment_id');

        if (is_array($environmentId) || filter_var($environmentId, FILTER_VALIDATE_INT) === false) {
            throw new NotFoundHttpException;
        }

        $environmentId = (int) $environmentId;

        $environment = ManagedEnvironment::query()
            ->whereKey($environmentId)
            ->where('workspace_id', $workspace->getKey())
            ->first();

        if (! $environment instanceof ManagedEnvironment) {
            throw new NotFoundHttpException;
        }

        $user = $request->user();

        if ($user instanceof User && ! $user->canAccessTenant($environment)) {
            throw new NotFoundHttpException;
        }

        return new self($environment);
    }

    public function environment(): ManagedEnvironment
    {
        return $this->environment;
    }

    public function environmentId(): int
    {
        return (int) $this->environment->getKey();
    }

    public function displayName(): string
    {
        return (string) ($this->environment->name ?: $this->environment->external_id ?: ('Environment '.$this->environmentId()));
    }

    /**
     * @template TModel of \Illuminate\Database\Eloquent\Model
     *
     * @param  Builder<TModel>  $query
     * @return Builder<TModel>
     */
    public function applyToQuery(Builder $query, string $column = 'managed_environment_id'): Builder
    {
        return $query->where($column, $this->environmentId());
    }

    public function queryParameters(): array
    {
        return [
            'environment_id' => $this->environmentId(),
        ];
    }

    public function clearUrl(string $url): string
    {
        return WorkspaceHubRegistry::cleanUrl($url);
    }
}
