"""Team repository"""
from typing import Optional, List
from sqlalchemy.orm import Session
from app.core.db.models.team import Team
from app.core.db.repositories.league_repository import LeagueRepository


class TeamRepository:
    """Repository for team operations"""
    
    def __init__(self, db: Session):
        self.db = db
    
    def get_by_id(self, team_id: int) -> Optional[Team]:
        """Get team by ID"""
        return self.db.query(Team).filter(Team.id == team_id).first()
    
    def get_by_source_id(self, source_id: str) -> Optional[Team]:
        """Get team by source ID"""
        return self.db.query(Team).filter(Team.source_id == source_id).first()
    
    def get_by_name(self, name: str) -> Optional[Team]:
        """Get team by name"""
        return self.db.query(Team).filter(Team.name == name).first()
    
    def create(self, team: Team) -> Team:
        """Create a new team"""
        self.db.add(team)
        self.db.commit()
        self.db.refresh(team)
        return team
    
    def get_or_create_by_source_id(self, source_id: str, name: str, country: Optional[str] = None) -> Team:
        """Get or create team by source ID

        `country` is a country name from the source; we map it to `countries`.
        """
        team = self.get_by_source_id(source_id)
        if team:
            return team

        country_id = None
        if country:
            lr = LeagueRepository(self.db)
            country_id = lr.get_or_create_country(country).id

        team = Team(
            source_id=source_id,
            name=name,
            country_id=country_id,
            code=f"team_{source_id}"
        )
        return self.create(team)

