"""
Unit tests for Match model.
"""

import pytest
from datetime import datetime, timezone
from sqlalchemy.orm import Session

from app.models.match import Match
from app.models.prediction import Prediction
from app.database import Base, engine, SessionLocal


@pytest.fixture(scope="function")
def db_session():
    """Create a fresh database session for each test."""
    # Create tables
    Base.metadata.create_all(bind=engine)
    
    # Create session
    session = SessionLocal()
    try:
        yield session
        session.rollback()
    finally:
        session.close()
        Base.metadata.drop_all(bind=engine)


class TestMatchModel:
    """Test Match SQLAlchemy model."""
    
    def test_match_creation(self, db_session: Session):
        """Test creating a match in database."""
        match = Match(
            home_team="PSG",
            away_team="Olympique de Marseille",
            date=datetime.now(timezone.utc),
            league="Ligue 1",
            status="scheduled"
        )
        
        db_session.add(match)
        db_session.commit()
        db_session.refresh(match)
        
        assert match.id is not None
        assert match.home_team == "PSG"
        assert match.away_team == "Olympique de Marseille"
        assert match.league == "Ligue 1"
        assert match.status == "scheduled"
    
    def test_match_required_fields(self, db_session: Session):
        """Test that all required fields must be provided."""
        # Missing home_team
        match = Match(
            away_team="Olympique de Marseille",
            date=datetime.now(timezone.utc),
            league="Ligue 1",
            status="scheduled"
        )
        
        db_session.add(match)
        
        with pytest.raises(Exception):  # IntegrityError expected
            db_session.commit()
    
    def test_match_to_dict(self, db_session: Session):
        """Test converting match to dictionary."""
        match = Match(
            home_team="Barcelona",
            away_team="Real Madrid",
            date=datetime.now(timezone.utc),
            league="La Liga",
            status="in_progress"
        )
        
        db_session.add(match)
        db_session.commit()
        db_session.refresh(match)
        
        match_dict = match.to_dict()
        
        assert match_dict['home_team'] == "Barcelona"
        assert match_dict['away_team'] == "Real Madrid"
        assert match_dict['league'] == "La Liga"
        assert match_dict['status'] == "in_progress"
        assert 'id' in match_dict
        assert 'date' in match_dict
    
    def test_match_repr(self, db_session: Session):
        """Test match __repr__ method."""
        match = Match(
            home_team="Manchester City",
            away_team="Liverpool",
            date=datetime.now(timezone.utc),
            league="Premier League",
            status="scheduled"
        )
        
        db_session.add(match)
        db_session.commit()
        db_session.refresh(match)
        
        repr_str = repr(match)
        
        assert "Match" in repr_str
        assert "id=" in repr_str
        assert "Manchester City" in repr_str
        assert "Liverpool" in repr_str
    
    def test_match_relationships(self, db_session: Session):
        """Test match relationships with predictions."""
        match = Match(
            home_team="Juventus",
            away_team="Inter Milan",
            date=datetime.now(timezone.utc),
            league="Serie A",
            status="scheduled"
        )
        
        db_session.add(match)
        db_session.commit()
        db_session.refresh(match)
        
        # Create predictions
        prediction1 = Prediction(
            match_id=match.id,
            energy_score="high",
            confidence="80%",
            predicted_winner="Juventus",
            created_at=datetime.now(timezone.utc)
        )
        
        prediction2 = Prediction(
            match_id=match.id,
            energy_score="medium",
            confidence="60%",
            predicted_winner="Inter Milan",
            created_at=datetime.now(timezone.utc)
        )
        
        db_session.add(prediction1)
        db_session.add(prediction2)
        db_session.commit()
        
        # Refresh match to load relationships
        db_session.refresh(match)
        
        assert len(match.predictions) == 2
        assert match.predictions[0].match_id == match.id
        assert match.predictions[1].match_id == match.id
