
from fastapi import HTTPException
from sqlalchemy import desc, select
from sqlalchemy.orm import Session
from app.api.pre_selected_category import schema
from app.api.store_formate import schemas
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 TblStoreFormat
from app.utils.schemas_utils import CustomResponse 

class PreSelectedCategoryService:
    def __init__(self, db: Session,token:JWTPayloadSchema):
        self.db = db
        self.token = token
        
    async def post(self, request:schemas.StoreFormateCreate11):
        group = self.db.query(TblGroup).filter(TblGroup.group_id == request.group_id).first()
        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
        }
        
        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]
        
        new_store = schemas.StoreFormateRes.model_validate(request)
        new_store.merchandise=str(merchandise_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.PRE_CREATE)
        
        
    # async def get_merchandise(self,group_id:int) -> list[schema.PreValidation]: 
        
    #     get_data = self.db.query(TblStoreFormat.merchandise).filter(TblStoreFormat.group_id == group_id).all()
    #     if not get_data:
    #         raise HTTPException(status_code=404, detail="not found")
    #     return [schema.PreValidation.model_validate(get_datas) for get_datas in get_data]
    
    async def get_pre_select_category(self, group_id: int) -> list[schema.PreValidation]:
        store_formats = (
            self.db.query(TblStoreFormat)
            .filter(TblStoreFormat.group_id == group_id)
            .all()
        )
 
        if not store_formats:
            raise HTTPException(status_code=404, detail="not found")
 
        group = self.db.query(TblGroup).filter(TblGroup.group_id == group_id).first()
        if not group:
            raise HTTPException(status_code=404, detail="Group not found")
 
        main_data = (
            self.db.query(TblMainData)
            .filter(
                (TblMainData.format_type == group.category_assigned)
                | (TblMainData.format_type == group.category)
            )
            .order_by(desc(TblMainData.data_id))
            .first()
        )
        if not main_data:
            raise HTTPException(status_code=404, detail="Main data not found")
 
        merchandise_map = {
            str(main_data.no_of_cats_l or 0): "Low",
            str(main_data.no_of_cats_m or 0): "Medium",
            str(main_data.no_of_cats_h or 0): "High",
        }
 
        response = []
        for sf in store_formats:
            response.append(
                schema.PreValidation(
                    store_format_type=sf.store_format_type,
                    merchandise=merchandise_map.get(sf.merchandise, "Unknown"),
                    merchandise_value=sf.merchandise
                )
            )
 
        return response
    