"""Tests for cross-model query conditions as documented in docs/*/api/dms/select.adoc.

Verifies that `.where()` correctly filters across object types within the same cabinet:

1. Search a document with conditions on its own fields + register fields + folder fields.
2. Search a folder that contains a document matching a condition.
3. Search a register that contains a document matching a condition.
4. Confirm that a parent register NOT in the direct hierarchy does NOT match
   (documents sit in sub-register → Unittest_DMS_Register is NOT the direct parent).
"""

import os
import unittest
from uuid import UUID

from ecmind_blue_client.ecm import ECM
from ecmind_blue_client.pool import SyncPoolClient
from tests.models.Unittest_DMS import (
    Unittest_DMS,
    Unittest_DMS_Document,
    Unittest_DMS_Register,
    Unittest_DMS_Subregister,
)
from tests._test_settings import ECM_SERVERS, ECM_USERNAME, ECM_PASSWORD


class TestCrossModelQuery(unittest.TestCase):
    """Integration tests for cross-model conditions in select().where()."""

    def setUp(self):
        self.client = SyncPoolClient(servers=ECM_SERVERS, username=ECM_USERNAME, password=ECM_PASSWORD)
        self.ecm = ECM(self.client)
        self.uuid = UUID(bytes=os.urandom(16), version=4)

        # Structure:  Folder → Register → SubRegister → Document
        self.folder = self.ecm.dms.insert_and_get(
            Unittest_DMS(Name=f"CrossQueryFolder_{self.uuid}")
        )
        self.register = self.ecm.dms.insert_and_get(
            Unittest_DMS_Register(Name=f"CrossQueryRegister_{self.uuid}"),
            folder_id=self.folder.system.id,
        )
        self.sub_register = self.ecm.dms.insert_and_get(
            Unittest_DMS_Subregister(Name=f"CrossQuerySubRegister_{self.uuid}"),
            folder_id=self.folder.system.id,
            register_id=self.register.system.id,
        )
        self.document = self.ecm.dms.insert_and_get(
            Unittest_DMS_Document(
                Name=f"CrossQueryDocument_{self.uuid}",
                StringField="CrossQueryValue",
            ),
            folder_id=self.folder.system.id,
            register_id=self.sub_register.system.id,
        )

    def tearDown(self):
        self.ecm.dms.delete(self.document)
        self.ecm.dms.delete(self.sub_register)
        self.ecm.dms.delete(self.register)
        self.ecm.dms.delete(self.folder)
        del self.client

    # ------------------------------------------------------------------
    # 1. Document query with conditions on sub-register and folder
    # ------------------------------------------------------------------

    def test_document_with_own_and_subregister_and_folder_conditions(self):
        """Documented claim: filter a document by its own fields + direct register + folder."""
        results = (
            self.ecm.dms.select(Unittest_DMS_Document)
            .where(
                Unittest_DMS_Document.StringField == "CrossQueryValue",
                Unittest_DMS_Subregister.Name == f"CrossQuerySubRegister_{self.uuid}",
                Unittest_DMS.Name == f"CrossQueryFolder_{self.uuid}",
            )
            .execute()
        )
        ids = [r.system.id for r in results]
        self.assertIn(self.document.system.id, ids, "Document should be found with all three conditions matching")

    def test_document_not_found_when_folder_condition_mismatches(self):
        """If the folder condition does not match, the document must not appear."""
        results = (
            self.ecm.dms.select(Unittest_DMS_Document)
            .where(
                Unittest_DMS_Document.StringField == "CrossQueryValue",
                Unittest_DMS.Name == "THIS_FOLDER_DOES_NOT_EXIST",
            )
            .execute()
        )
        ids = [r.system.id for r in results]
        self.assertNotIn(self.document.system.id, ids, "Document must not appear when folder condition does not match")

    def test_document_not_found_when_register_condition_mismatches(self):
        """If the direct register condition does not match, the document must not appear."""
        results = (
            self.ecm.dms.select(Unittest_DMS_Document)
            .where(
                Unittest_DMS_Document.StringField == "CrossQueryValue",
                Unittest_DMS_Subregister.Name == "THIS_REGISTER_DOES_NOT_EXIST",
            )
            .execute()
        )
        ids = [r.system.id for r in results]
        self.assertNotIn(self.document.system.id, ids, "Document must not appear when direct register condition does not match")

    # ------------------------------------------------------------------
    # 2. Folder query with a condition on a child document
    # ------------------------------------------------------------------

    def test_folder_found_via_child_document_condition(self):
        """Documented claim: select a folder that contains a document matching a condition."""
        results = (
            self.ecm.dms.select(Unittest_DMS)
            .where(
                Unittest_DMS.Name == f"CrossQueryFolder_{self.uuid}",
                Unittest_DMS_Document.StringField == "CrossQueryValue",
            )
            .execute()
        )
        ids = [r.system.id for r in results]
        self.assertIn(self.folder.system.id, ids, "Folder should be found via child document condition")

    def test_folder_not_found_when_child_document_condition_mismatches(self):
        """Folder must not be found if no child document satisfies the condition."""
        results = (
            self.ecm.dms.select(Unittest_DMS)
            .where(
                Unittest_DMS.Name == f"CrossQueryFolder_{self.uuid}",
                Unittest_DMS_Document.StringField == "THIS_VALUE_DOES_NOT_EXIST",
            )
            .execute()
        )
        ids = [r.system.id for r in results]
        self.assertNotIn(self.folder.system.id, ids, "Folder must not appear when no child document matches")

    # ------------------------------------------------------------------
    # 3. Register query with a condition on a child document
    # ------------------------------------------------------------------

    def test_subregister_found_via_child_document_condition(self):
        """Documented claim: select a register that contains a document matching a condition."""
        results = (
            self.ecm.dms.select(Unittest_DMS_Subregister)
            .where(
                Unittest_DMS_Subregister.Name == f"CrossQuerySubRegister_{self.uuid}",
                Unittest_DMS_Document.StringField == "CrossQueryValue",
            )
            .execute()
        )
        ids = [r.system.id for r in results]
        self.assertIn(self.sub_register.system.id, ids, "SubRegister should be found via child document condition")

    # ------------------------------------------------------------------
    # 4. Constraint: parent register above direct parent is NOT evaluated
    # ------------------------------------------------------------------

    def test_parent_register_above_direct_parent_is_not_matched(self):
        """Documented constraint: only the directly enclosing register is available.

        The document sits in sub_register (Unittest_DMS_Subregister).
        Unittest_DMS_Register is one level above and must NOT act as a filter.
        Filtering by Unittest_DMS_Register should return 0 results for this document
        because Unittest_DMS_Register is not the direct parent of the document.
        """
        results = (
            self.ecm.dms.select(Unittest_DMS_Document)
            .where(
                Unittest_DMS_Document.StringField == "CrossQueryValue",
                Unittest_DMS_Register.Name == f"CrossQueryRegister_{self.uuid}",
            )
            .execute()
        )
        ids = [r.system.id for r in results]
        self.assertNotIn(
            self.document.system.id,
            ids,
            "Document must not be found via a non-direct parent register condition",
        )


if __name__ == "__main__":
    unittest.main(verbosity=2)
