from sqlalchemy import desc, select
import app.api.store_formate.schemas as schemas
from sqlalchemy.orm import Session
from app.dependency.authantication import JWTPayloadSchema
from app.locale.messages import Messages
from app.models.main.group import TblGroup
from app.models.main.main_data import TblMainData
from app.models.main.store_formate import StoreFormatBase, TblStoreFormat
from app.utils.schemas_utils import CustomResponse 
from app.api.store_formate.schemas import StoreFormateRes

class StoreFormateService:
    def __init__(self, db: Session,token:JWTPayloadSchema):
        self.db = db
        self.token = token

    async def create_store_formate(self, request: schemas.StoreFormateCreate):
        created_user = StoreFormatBase.model_validate(request) 
        TblStoreFormat.create(created_user, self.db)
        self.db.commit()  
        return CustomResponse(status="1", message=Messages.STOREFORMATE_CREAT) 
    
    def create_store_format3(self, request: schemas.StoreFormateCreate11):
        group = self.db.execute(
            select(TblGroup).where(TblGroup.group_id == request.group_id)
        ).scalar_one_or_none()

        if not group:
            return CustomResponse(status="0", message="Group not found")

        result = self.db.execute(
            select(TblMainData)
            .where(
                (TblMainData.format_type == group.category_assigned) |
                (TblMainData.format_type == group.category)
            )
            .order_by(desc(TblMainData.data_id))
            .limit(1)
        )

        main_data = result.scalar_one_or_none()

        if not main_data:
            return CustomResponse(status="0", message="Main data not found for the group's category")
            
        merchandise_map = {
            'Low': main_data.no_of_cats_l or 0,
            'Medium': main_data.no_of_cats_m or 0,
            'High': main_data.no_of_cats_h or 0
        }

        service_parameters_map = {
            'Low': main_data.services_l or 0,
            'Medium': main_data.services_m or 0,
            'High': main_data.services_h or 0
        }

        technology_adoption_map = {
            'Low': main_data.tech_inv_l or 0,
            'Medium': main_data.tech_inv_m or 0,
            'High': main_data.tech_inv_h or 0
        }

        merchandise_text = request.merchandise
        if merchandise_text not in merchandise_map:
            return CustomResponse(status="0", message="Invalid merchandise value (Low, Medium, High required)")
        merchandise_value = merchandise_map[merchandise_text]

        service_text = request.service_parameters
        if service_text not in service_parameters_map:
            return CustomResponse(status="0", message="Invalid service parameters value (Low, Medium, High required)")
        service_value = service_parameters_map[service_text]

        tech_text = request.technology_adoption
        if tech_text not in technology_adoption_map:
            return CustomResponse(status="0", message="Invalid technology adoption value (Low, Medium, High required)")
        tech_value = technology_adoption_map[tech_text]

        new_store = StoreFormateRes.model_validate(request)
        new_store.merchandise=str(merchandise_value)
        new_store.service_parameters=str(service_value)
        new_store.technology_adoption=str(tech_value)
        new_store_db = TblStoreFormat(**new_store.model_dump())
        self.db.add(new_store_db)
        self.db.commit()
        self.db.refresh(new_store_db)
        return CustomResponse(status="1", message=Messages.STOREFORMATE_CREAT)

    async def update_store_formate(self, request: schemas.StoreFormateUpdate):
        if request.store_id is None:
            return CustomResponse(status="-1", message=Messages.STUDENT_ID_REQUIED)
        updated_data = TblStoreFormat.update(request.store_id, request, self.db)
        response_data = schemas.StoreFormateResponse.model_validate(updated_data)
        return CustomResponse(status="1",message="Store format updated successfully",data=response_data.model_dump())
    
    async def get_store_formate(self, store_id: int):
        store_format = TblStoreFormat.get_by_id(store_id, self.db)
        return schemas.StoreFormateResponse.model_validate(store_format)
    
    async def delete_store_formate(self, store_id: int):
        deleted = TblStoreFormat.delete(store_id, self.db)
        if not deleted:
            return CustomResponse(status="-1", message="Store Formate not found")
        return CustomResponse(status="1", message="Store Formate deleted successfully")


