from sqlalchemy import func, or_, select from sqlalchemy.orm import Session from app.models.site import Site class SitesRepository: def __init__(self, db: Session) -> None: self.db = db def get_by_key(self, site_key: str) -> Site | None: return self.db.scalar(select(Site).where(Site.site_key == site_key)) def get_by_id(self, site_id: str) -> Site | None: return self.db.scalar(select(Site).where(Site.id == site_id)) def list( self, *, keyword: str | None = None, company_id: str | None = None, limit: int = 100, offset: int = 0, ) -> tuple[list[Site], int]: stmt = select(Site) count_stmt = select(func.count()).select_from(Site) if keyword: pattern = f"%{keyword}%" cond = or_(Site.site_key.ilike(pattern), Site.display_name.ilike(pattern), Site.domain.ilike(pattern)) stmt = stmt.where(cond) count_stmt = count_stmt.where(cond) if company_id: stmt = stmt.where(Site.company_id == company_id) count_stmt = count_stmt.where(Site.company_id == company_id) stmt = stmt.order_by(Site.created_at.desc()).limit(limit).offset(offset) return list(self.db.scalars(stmt).all()), int(self.db.scalar(count_stmt) or 0) def create( self, *, site_key: str, company_id: str, display_name: str, domain: str | None, status: str = "active", ) -> Site: item = Site(site_key=site_key, company_id=company_id, display_name=display_name, domain=domain, status=status) self.db.add(item) self.db.commit() self.db.refresh(item) return item def update( self, item: Site, *, company_id: str | None = None, display_name: str | None = None, domain: str | None = None, idp_group_id: str | None = None, status: str | None = None, ) -> Site: if company_id is not None: item.company_id = company_id if display_name is not None: item.display_name = display_name if domain is not None: item.domain = domain if idp_group_id is not None: item.idp_group_id = idp_group_id if status is not None: item.status = status self.db.commit() self.db.refresh(item) return item def delete(self, item: Site) -> None: self.db.delete(item) self.db.commit()