from typing import List, Optional, Tuple, Dict, Any
from sqlalchemy.orm import Session
from sqlalchemy import select

from .models import INPC
from .dto import INPCCreate, INPCUpdate


class INPCService:
    @staticmethod
    def get_all(
        db: Session,
        tenant_id: int,
        company_id: int,
        skip: int = 0,
        limit: int = 100,
        filters: Optional[Dict[str, Any]] = None
    ) -> Tuple[List[INPC], int]:
        query = db.query(INPC).filter(
            INPC.tenant_id == tenant_id,
            INPC.company_id == company_id
        )

        if filters:
            # Add filters here if needed
            pass

        total = query.count()
        items = query.offset(skip).limit(limit).all()
        return items, total

    @staticmethod
    def get_by_id(
        db: Session,
        id: int,
        tenant_id: int,
        company_id: int
    ) -> Optional[INPC]:
        return db.query(INPC).filter(
            INPC.id == id,
            INPC.tenant_id == tenant_id,
            INPC.company_id == company_id
        ).first()

    @staticmethod
    def create(
        db: Session,
        data: INPCCreate,
        tenant_id: int,
        company_id: int
    ) -> INPC:
        db_obj = INPC(
            **data.model_dump(),
            tenant_id=tenant_id,
            company_id=company_id
        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    @staticmethod
    def update(
        db: Session,
        id: int,
        tenant_id: int,
        data: INPCUpdate,
        company_id: int
    ) -> Optional[INPC]:
        db_obj = INPCService.get_by_id(db, id, tenant_id, company_id)
        if not db_obj:
            return None

        update_dict = data.model_dump(exclude_unset=True)
        for key, value in update_dict.items():
            setattr(db_obj, key, value)

        db.commit()
        db.refresh(db_obj)
        return db_obj

    @staticmethod
    def delete(
        db: Session,
        id: int,
        tenant_id: int,
        company_id: int
    ) -> bool:
        db_obj = INPCService.get_by_id(db, id, tenant_id, company_id)
        if not db_obj:
            return False

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