from __future__ import annotations

import tempfile
import unittest
from pathlib import Path

from backend.features.alerts.service import AlertService
from backend.bootstrap.container import build_application_container
from backend.database.repositories import (
    SQLiteAlertRepository,
    SQLiteStrategyTrackingRepository,
    SQLiteTradeJournalRepository,
)
from database import ReviewDatabase


class RepositoryBoundaryTests(unittest.TestCase):
    def setUp(self) -> None:
        self.temporary = tempfile.TemporaryDirectory()
        self.addCleanup(self.temporary.cleanup)
        self.database = ReviewDatabase(Path(self.temporary.name) / "review.db")

    def test_container_injects_narrow_user_repositories(self) -> None:
        skills = Path(self.temporary.name) / "skills"
        private = Path(self.temporary.name) / "private"
        skills.mkdir()
        private.mkdir()
        container = build_application_container(self.database, {}, skills, private)
        self.assertIsInstance(container.repositories.alerts, SQLiteAlertRepository)
        self.assertIsInstance(container.repositories.trades, SQLiteTradeJournalRepository)
        self.assertIsInstance(
            container.repositories.strategy_tracking, SQLiteStrategyTrackingRepository
        )
        self.assertIs(container.alert_service.repository, container.repositories.alerts)
        self.assertIs(container.trade_journal.repository, container.repositories.trades)

    def test_private_repositories_reject_missing_account_owner(self) -> None:
        alerts = SQLiteAlertRepository(self.database)
        trades = SQLiteTradeJournalRepository(self.database)
        tracking = SQLiteStrategyTrackingRepository(self.database)
        with self.assertRaises(ValueError):
            alerts.list_alerts(0, "20260729")
        with self.assertRaises(ValueError):
            trades.list_trade_entries(0)
        with self.assertRaises(ValueError):
            tracking.list_strategy_tracks(0)

    def test_alert_service_keeps_database_compatible_structural_port(self) -> None:
        service = AlertService(self.database)
        self.assertIs(service.repository, self.database)


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