"""
Service layer for Seal.
"""

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

from sqlalchemy.orm import Session

from . import dto, models


class SealService:
    """Service for Seal 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.Seal], int]:
        """Get all seals for a tenant/company with pagination"""
        query = db.query(models.Seal).filter(
            models.Seal.tenant_id == tenant_id,
            models.Seal.company_id == company_id,
        )

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

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

        return seals, total

    @staticmethod
    def get_by_id(
        db: Session, seal_id: int, tenant_id: int, company_id: int
    ) -> Optional[models.Seal]:
        """Get seal by ID"""
        return (
            db.query(models.Seal)
            .filter(
                models.Seal.id == seal_id,
                models.Seal.tenant_id == tenant_id,
                models.Seal.company_id == company_id,
            )
            .first()
        )

    @staticmethod
    def create(
        db: Session,
        seal_data: dto.SealCreateDTO,
        tenant_id: int,
        company_id: int,
    ) -> models.Seal:
        """Create a new seal"""
        new_seal = models.Seal(
            **seal_data.model_dump(), tenant_id=tenant_id, company_id=company_id
        )
        db.add(new_seal)
        db.commit()
        db.refresh(new_seal)
        return new_seal

    @staticmethod
    def update(
        db: Session,
        seal_id: int,
        tenant_id: int,
        seal_data: dto.SealUpdateDTO,
        company_id: int,
    ) -> Optional[models.Seal]:
        """Update a seal"""
        seal = SealService.get_by_id(db, seal_id, tenant_id, company_id)
        if not seal:
            return None

        # Update fields
        update_data = seal_data.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            setattr(seal, field, value)

        db.commit()
        db.refresh(seal)
        return seal

    @staticmethod
    def delete(
        db: Session, seal_id: int, tenant_id: int, company_id: int
    ) -> bool:
        """Delete a seal"""
        seal = SealService.get_by_id(db, seal_id, tenant_id, company_id)
        if not seal:
            return False

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