from typing import List
from sqlalchemy import func
from app.api.display_racking_create import schemas
from app.api.display_racking_create.schemas import DisplayRackingUnitCreate,DisplayRackingUnitResponce
from app.models.main.display_racking_unit import DisplayRackingUnitBase, TblDisplayRackingUnit
from app.utils.schemas_utils import CustomResponse
from app.locale.messages import Messages
from sqlalchemy.orm import Session
from app.dependency.authantication import JWTPayloadSchema
from fastapi import HTTPException

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

    async def create_display_racking_unit(self, request: DisplayRackingUnitCreate):
        total = request.cost_per_unit * request.number_of_units
        rack_data = DisplayRackingUnitBase(
            group_id=request.group_id,
            store_format_type=request.store_format_type,
            type_display_racking_unit=request.type_display_racking_unit,
          
            number_of_units=request.number_of_units,
            cost_per_unit=request.cost_per_unit,
            total=total,
            remarks=request.remarks,
        )
        rack_record = TblDisplayRackingUnit.create(rack_data, self.db)
        self.db.commit()
        self.db.refresh(rack_record)
        response = DisplayRackingUnitResponce.model_validate(rack_record, from_attributes=True)
        return CustomResponse(status="1", message="Display and Racking units saved Successfully", data=response)
    
    async def get_racking_by_group_id(self, group_id: int):
        geted =TblDisplayRackingUnit.get_unit(group_id, self.db)
        if not geted:
            raise HTTPException(status_code=404, detail="Get group ID not found")
        return [DisplayRackingUnitResponce.model_validate(get_group) for get_group in geted]

    def get_subtotal_by_store_format(self, group_id: int):
        results = (
            self.db.query(
                TblDisplayRackingUnit.store_format_type,
                func.sum(TblDisplayRackingUnit.total).label("subtotal")
            )
            .filter(TblDisplayRackingUnit.group_id == group_id)
            .group_by(TblDisplayRackingUnit.store_format_type)
            .all()
        )

        return [
            {"store_format_type": store_format_type, "subtotal": subtotal or 0.0}
            for store_format_type, subtotal in results
        ] 
        
        
    async def update(self, request:List[schemas.DisplayRackingUnitUpdate]):
        for req in request:
            updated = DisplayRackingUnitBase.model_validate(req.model_dump())
            if updated.rack_id is None:
                return CustomResponse(status="-1", message=Messages.DISPLAY_RACKING_NOT)   
            TblDisplayRackingUnit.update_unit(updated.rack_id, updated, self.db)
        self.db.commit()
        return CustomResponse(status="1", message=Messages.DISPLAY_RACKING_UPDATE)
    
    async def delete(self, rack_id:int):
        deleted = TblDisplayRackingUnit.delete_unit(rack_id, self.db)
        if not deleted:
            return CustomResponse(status="-1", message=Messages.DISPLAY_RACKING_NOT)
        return CustomResponse(status="1", message=Messages.DISPLAY_RACKING_DELETE)
        