from typing import List, Tuple

from sqlalchemy.orm import Session
from sqlalchemy import or_

from . import dto, models


class TrailerTypeService:
    @staticmethod
    def list_trailer_types(
        db: Session, skip: int = 0, limit: int = 50, search: str = None
    ) -> Tuple[List[models.TrailerType], int]:
        q = db.query(models.TrailerType).order_by(models.TrailerType.trailer_type_key)
        
        if search:
            search_filter = f"%{search}%"
            q = q.filter(
                or_(
                    models.TrailerType.trailer_type_key.ilike(search_filter),
                    models.TrailerType.description.ilike(search_filter)
                )
            )
            
        total = q.count()
        items = q.offset(skip).limit(limit).all()
        return items, total

    @staticmethod
    def get_trailer_type_by_key(db: Session, trailer_type_key: str):
        return (
            db.query(models.TrailerType)
            .filter(models.TrailerType.trailer_type_key == trailer_type_key)
            .first()
        )

    @staticmethod
    def create_trailer_type(db: Session, trailer_type_data: dto.TrailerTypeCreateDTO):
        new_trailer_type = models.TrailerType(**trailer_type_data.dict())
        db.add(new_trailer_type)
        db.commit()
        db.refresh(new_trailer_type)
        return new_trailer_type

    @staticmethod
    def delete_trailer_type(db: Session, trailer_type_key: str):
        trailer_type = TrailerTypeService.get_trailer_type_by_key(db, trailer_type_key)
        if trailer_type:
            db.delete(trailer_type)
            db.commit()
        return trailer_type
