"""Integration tests for ECMDmsSync.select_lol().

Requires a running ECM server at localhost:4000.
"""

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
from tests._test_settings import ECM_SERVERS, ECM_USERNAME, ECM_PASSWORD


class TestEcmDmsSelectLolSync(unittest.TestCase):
    """Integration tests for ECMDmsSync.select_lol() — requires localhost:4000."""

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

        folder_id, folder_type_id = self.ecm.dms.insert(Unittest_DMS(Name=self.folder_name))
        self.folder_id = folder_id
        self.folder_type_id = folder_type_id

    def tearDown(self):
        folder = self.ecm.dms.get(Unittest_DMS, self.folder_id, self.folder_type_id)
        self.ecm.dms.delete(folder, hard_delete=True)
        del self.client

    def test_select_lol_returns_list(self):
        """select_lol().execute() returns a list."""
        result = self.ecm.dms.select_lol(Unittest_DMS).execute()

        self.assertIsInstance(result, list)

    def test_select_lol_where_returns_matching_folder(self):
        """A where() condition filters the result to the expected folder."""
        result = self.ecm.dms.select_lol(Unittest_DMS).where(
            Unittest_DMS.Name == self.folder_name
        ).execute()

        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].Name, self.folder_name)

    def test_select_lol_where_no_match_returns_empty(self):
        """A where() condition with no matching object returns an empty list."""
        result = self.ecm.dms.select_lol(Unittest_DMS).where(
            Unittest_DMS.Name == "__nonexistent_folder__"
        ).execute()

        self.assertIsInstance(result, list)
        self.assertEqual(len(result), 0)

    def test_select_lol_stream_yields_items(self):
        """stream() yields the same results as execute()."""
        items = list(
            self.ecm.dms.select_lol(Unittest_DMS).where(
                Unittest_DMS.Name == self.folder_name
            ).stream()
        )

        self.assertEqual(len(items), 1)
        self.assertEqual(items[0].Name, self.folder_name)
