from typing import Optional, Tuple, List, Dict, Any

from sqlalchemy.orm import Session

from . import dto, models


class TransporterService:
    """Service for Transporter CRUD operations with tenant support"""

    @staticmethod
    def get_all(
        db: Session,
        tenant_id: int,
        company_id: int,
        skip: int = 0,
        limit: int = 50,
        filters: Optional[Dict[str, Any]] = None,
    ) -> Tuple[List[models.Transporter], int]:
        """Get all transporters for a tenant/company with pagination"""
        query = db.query(models.Transporter).filter(
            models.Transporter.tenant_id == tenant_id,
            models.Transporter.company_id == company_id,
        )

        # Apply filters if provided
        if filters:
            if filters.get("name"):
                query = query.filter(
                    models.Transporter.name.ilike(f"%{filters['name']}%")
                )
            if filters.get("rfc"):
                query = query.filter(
                    models.Transporter.rfc.ilike(f"%{filters['rfc']}%")
                )

        total = query.count()
        transporters = query.offset(skip).limit(limit).all()

        return transporters, total

    @staticmethod
    def get_by_id(
        db: Session, transporter_key: str, tenant_id: int, company_id: int
    ) -> Optional[models.Transporter]:
        """Get transporter by transporter_key"""
        return (
            db.query(models.Transporter)
            .filter(
                models.Transporter.transporter_key == transporter_key,
                models.Transporter.tenant_id == tenant_id,
                models.Transporter.company_id == company_id,
            )
            .first()
        )

    @staticmethod
    def create(
        db: Session,
        transporter_data: dto.TransporterCreateDTO,
        tenant_id: int,
        company_id: int,
    ) -> models.Transporter:
        """Create a new transporter"""
        new_transporter = models.Transporter(
            **transporter_data.model_dump(), tenant_id=tenant_id, company_id=company_id
        )
        db.add(new_transporter)
        db.commit()
        db.refresh(new_transporter)
        return new_transporter

    @staticmethod
    def update(
        db: Session,
        transporter_key: str,
        tenant_id: int,
        company_id: int,
        transporter_data: dto.TransporterUpdateDTO,
    ) -> Optional[models.Transporter]:
        """Update a transporter"""
        transporter = TransporterService.get_by_id(
            db, transporter_key, tenant_id, company_id
        )
        if not transporter:
            return None

        # Update fields (excluding transporter_key as it's the primary key)
        update_data = transporter_data.model_dump(
            exclude_unset=True, exclude={"transporter_key"}
        )
        for field, value in update_data.items():
            setattr(transporter, field, value)

        db.commit()
        db.refresh(transporter)
        return transporter

    @staticmethod
    def delete(
        db: Session, transporter_key: str, tenant_id: int, company_id: int
    ) -> bool:
        """Delete a transporter"""
        transporter = TransporterService.get_by_id(
            db, transporter_key, tenant_id, company_id
        )
        if not transporter:
            return False

        db.delete(transporter)
        db.commit()
        return True
