from typing import List
from sqlalchemy.orm import Session
from app.api.critical_for_business import schema
from app.dependency.authantication import JWTPayloadSchema
from app.models.main.critical_for_business import CriticalBusinessBase, TblCriticalBusiness
from app.utils.schemas_utils import CustomResponse
from app.locale.messages import Messages
from fastapi import HTTPException

class CriticalBusinessService:
    def __init__(self, db:Session, token:JWTPayloadSchema):
        self.db = db
        self.token = token
        
    async def created(self, request:List[schema.CriticalBusinessCreate]):
        created_data = []
        for item in request:
            create_request = CriticalBusinessBase.model_validate(item.model_dump())
            sale = TblCriticalBusiness.create(create_request, self.db)
            created_data.append(sale)
        self.db.commit()
        return CustomResponse(status="1", message=Messages.CRITICAL_BUSINESS)
    
    async def geted(self, group_id:int):
        geted_data = TblCriticalBusiness.get(group_id, self.db)
        if not geted_data:
            raise HTTPException(status_code=404, detail="Get group ID not found")
        return [schema.CriticalBusinessResponse.model_validate(get_group) for get_group in geted_data]
    
    async def updated(self, request:List[schema.CriticalBusinessUpdate]):
        for req in request:
            updated_data = CriticalBusinessBase.model_validate(req.model_dump())
            if updated_data.critical_id is None:
                return CustomResponse(status="-1", message=Messages.CRITICAL_BUSINESS_NOT)
            TblCriticalBusiness.update(updated_data.critical_id, updated_data, self.db)
        self.db.commit()
        return CustomResponse(status="1", message=Messages.CRITICAL_BUSINESS_UPDATE)
    
    async def deleted(self, critical_id:int):
        deleted_data = TblCriticalBusiness.delete(critical_id, self.db)
        if not deleted_data:
            return CustomResponse(status="-1", message=Messages.CRITICAL_BUSINESS_NOT)
        return CustomResponse(status="1", message=Messages.CRITICAL_BUSINESS_DELETE)