# Copyright 2025 Softwell S.r.l.
# Licensed under the Apache License, Version 2.0

"""Tests for CLI REPL parsing logic."""

from __future__ import annotations

import pytest

from genro_cli.cli import Repl
from unittest.mock import AsyncMock


class TestParseInvocation:
    """Test the _parse_invocation method of Repl."""

    def setup_method(self) -> None:
        conn = AsyncMock()
        self.repl = Repl(conn)

    def test_simple_path(self) -> None:
        path, query, data = self.repl._parse_invocation("/api/users")
        assert path == "/api/users"
        assert query is None
        assert data is None

    def test_path_without_slash(self) -> None:
        path, query, data = self.repl._parse_invocation("api/users")
        assert path == "/api/users"

    def test_path_with_query(self) -> None:
        path, query, data = self.repl._parse_invocation("/api/users?limit=10&offset=0")
        assert path == "/api/users"
        assert query == {"limit": "10", "offset": "0"}
        assert data is None

    def test_path_with_json_body(self) -> None:
        path, query, data = self.repl._parse_invocation('/api/users {"name":"Alice"}')
        assert path == "/api/users"
        assert query is None
        assert data == {"name": "Alice"}

    def test_path_with_query_and_body(self) -> None:
        path, query, data = self.repl._parse_invocation(
            '/api/users?role=admin {"name":"Alice"}'
        )
        assert path == "/api/users"
        assert query == {"role": "admin"}
        assert data == {"name": "Alice"}

    def test_invalid_json_body(self) -> None:
        with pytest.raises(ValueError, match="Invalid JSON body"):
            self.repl._parse_invocation("/api/users {invalid}")

    def test_empty_path(self) -> None:
        path, query, data = self.repl._parse_invocation("")
        assert path == "/"
        assert query is None
        assert data is None
