from __future__ import annotations

from unittest import mock

from django.test import SimpleTestCase

from uksi_browser import services


class ServiceTests(SimpleTestCase):
    def test_browse_children_returns_taxon_summary(self) -> None:
        sample_rows = [
            {
                "taxon_id": "1",
                "scientific_name": "Plantae",
                "taxon_rank": "kingdom",
                "taxonomic_status": "accepted",
            }
        ]
        with mock.patch("uksi_browser.dao.get_children", return_value=sample_rows):
            results = services.browse_children("root")
        self.assertEqual(len(results), 1)
        summary = results[0]
        self.assertEqual(summary.taxon_id, "1")
        self.assertEqual(summary.label, "Plantae")
        self.assertEqual(summary.rank, "kingdom")

    def test_search_combines_sources(self) -> None:
        taxa_rows = [
            {
                "taxon_id": "1",
                "scientific_name": "Quercus robur",
                "taxon_rank": "species",
                "taxonomic_status": "accepted",
                "authorship": "L.",
            }
        ]
        vernacular_rows = [
            {
                "taxon_id": "1",
                "vernacular_name": "English oak",
                "language": "en",
                "scientific_name": "Quercus robur",
                "taxon_rank": "species",
                "taxonomic_status": "accepted",
            }
        ]
        fuzzy_rows = [
            {
                "taxon_id": "2",
                "scientific_name": "Quercus rubra",
                "taxon_rank": "species",
                "authorship": "L.",
            }
        ]
        with mock.patch("uksi_browser.dao.search_taxa", return_value=taxa_rows), mock.patch(
            "uksi_browser.dao.search_by_vernacular", return_value=vernacular_rows
        ), mock.patch("uksi_browser.dao.fuzzy_candidates", return_value=fuzzy_rows):
            results = services.search("quercus")

        self.assertEqual(results.query, "quercus")
        self.assertEqual(len(results.taxa_matches), 1)
        self.assertEqual(len(results.vernacular_matches), 1)
        self.assertEqual(len(results.fuzzy_matches), 1)
