from typing import List, Optional

from sqlalchemy.orm import Session

from app.core.entities.federal_district import FederalDistrictEntity
from app.infrastructure.database.models.federal_districts import FederalDistrict
from app.infrastructure.database.repository.federal_district_repository import FederalDistrictsRepository


class FederalDistrictsService:
    def __init__(self, db: Session):
        self.repository = FederalDistrictsRepository(db)

    def get_all_federal_districts(self) -> List[FederalDistrictEntity]:
        federal_districts = self.repository.get_all()
        return [
            FederalDistrictEntity(
                id=fd.id,
                name=fd.name,
                cities=[city.id for city in fd.cities] if fd.cities else []
            )
            for fd in federal_districts
        ]

    def get_federal_district_by_id(self, federal_district_id: int) -> Optional[FederalDistrictEntity]:
        federal_district = self.repository.get_by_id(federal_district_id)
        if federal_district:
            return FederalDistrictEntity(
                id=federal_district.id,
                name=federal_district.name,
                cities=[city.id for city in federal_district.cities] if federal_district.cities else []
            )
        return None

    def create_federal_district(self, entity: FederalDistrictEntity) -> FederalDistrictEntity:
        federal_district_model = FederalDistrict(
            name=entity.name
        )
        created_federal_district = self.repository.create(federal_district_model)
        return FederalDistrictEntity(
            id=created_federal_district.id,
            name=created_federal_district.name,
            cities=[]  
        )

    def update_federal_district(self, federal_district_id: int, entity: FederalDistrictEntity) -> Optional[FederalDistrictEntity]:
        federal_district_model = self.repository.get_by_id(federal_district_id)
        if federal_district_model:
            federal_district_model.name = entity.name
            self.repository.update(federal_district_model)
            return FederalDistrictEntity(
                id=federal_district_model.id,
                name=federal_district_model.name,
                cities=[city.id for city in federal_district_model.cities] if federal_district_model.cities else []
            )
        return None

    def delete_federal_district(self, federal_district_id: int) -> bool:
        return self.repository.delete(federal_district_id) is not None
