from sqlalchemy import asc
from sqlalchemy.orm import Session, joinedload
from app.infrastructure.database.models.cities import City


class CityRepository:
    def __init__(self, db: Session):
        self.db = db

    def get_all(self):
        return self.db.query(City).all()

    def get_by_name(self, city_name):
        return self.db.query(City).filter(City.name == city_name).first()

    def get_all_with_federal_district(self):
        return self.db.query(City) \
            .options(joinedload(City.federal_district)) \
            .order_by(asc(City.id)) \
            .all()

    def get_by_id(self, city_id: int):
        return self.db.query(City).filter(City.id == city_id).first()

    def create(self, city: City):
        self.db.add(city)
        self.db.commit()
        self.db.refresh(city)
        return city

    def update(self, city: City):
        self.db.commit()
        return city

    def delete(self, city_id: int):
        city = self.db.query(City).filter(City.id == city_id).first()
        if city:
            self.db.delete(city)
            self.db.commit()
            return city
        return None
