<?php

namespace App\Support\Workspaces;

use App\Models\Workspace;

final class WorkspaceResolver
{
    public function resolve(string $value): ?Workspace
    {
        $value = $this->normalizeRouteValue($value);

        $workspace = Workspace::query()
            ->where('slug', $value)
            ->first();

        if ($workspace !== null) {
            return $workspace;
        }

        if (! ctype_digit($value)) {
            return null;
        }

        return Workspace::query()->whereKey((int) $value)->first();
    }

    private function normalizeRouteValue(string $value): string
    {
        $value = trim($value);

        if (! str_starts_with($value, '{')) {
            return $value;
        }

        $decoded = json_decode($value, true);

        if (! is_array($decoded)) {
            return $value;
        }

        $slug = $decoded['slug'] ?? null;

        if (is_string($slug) && $slug !== '') {
            return $slug;
        }

        $id = $decoded['id'] ?? null;

        if (is_int($id)) {
            return (string) $id;
        }

        if (is_string($id) && ctype_digit($id)) {
            return $id;
        }

        return $value;
    }
}
