from typing import List
from fastapi import HTTPException
from sqlalchemy import func
from sqlalchemy.orm import Session
from app.api.info_tech import schema
from app.dependency.authantication import JWTPayloadSchema
from app.locale.messages import Messages
from app.models.main.info_tech import InfoTechBase, TblInfoTech
from app.utils.schemas_utils import CustomResponse

class InfoTechService:
    def __init__(self, db:Session, token:JWTPayloadSchema):
        self.db = db
        self.token = token
        
    async def create_info_tech(self, request:List[schema.InfoTechCreate]):
        created_info = []
        for item in request:
            total = item.units * item.cost_per_unit
            request_data = item.model_dump()
            request_data["total"] = total
            create_item = InfoTechBase.model_validate(request_data)
            sale = TblInfoTech.create(create_item, self.db)
            created_info.append(sale)
        self.db.commit()
        return CustomResponse(status="1", message=Messages.INFO_TECH_CREATE)
    
    async def get_info_tech(self, group_id:int):
        new_get_info_tech = TblInfoTech.get_info_tech_data(group_id, self.db)
        if new_get_info_tech is None:
            raise HTTPException(status_code=404, detail="InfoTech data not found")
        return [schema.InfoTechResponses.model_validate(get_group) for get_group in new_get_info_tech]
    
    # async def get_and_sum_info_tech(self, group_id: int):
    #     result = (
    #         self.db.query(
    #             TblInfoTech.store_format_type,        # DB column
    #             func.sum(TblInfoTech.total).label("total_sum")
    #         )
    #         .filter(TblInfoTech.group_id == group_id)
    #         .group_by(TblInfoTech.store_format_type)
    #         .all()
    #     )

    #     # Map to correct attribute name
    #     mapped = []
    #     for r in result:
    #         mapped.append(
    #             type("Obj", (), {
    #                 "store_format_type": r.store_format_type,
    #                 "total_sum": r.total_sum
    #             })
    #         )
    #     return mapped
    
    async def get_and_sum_info_tech(self, group_id:int) ->"TblInfoTech":
        new_get_and_sum_info_tech = (
            self.db.query(
                TblInfoTech.group_id,
                TblInfoTech.store_format_type,
                func.sum(TblInfoTech.total).label("total_sum")
            )
            .filter(TblInfoTech.group_id == group_id)
            .group_by(TblInfoTech.group_id,TblInfoTech.store_format_type)
            .all()
        )
        if not new_get_and_sum_info_tech:
            raise HTTPException(status_code=404, detail="Get sum ID not found")
        return [schema.InfoTechSum.model_validate(get_and_sum_info_tech) for get_and_sum_info_tech in new_get_and_sum_info_tech]
    
    async def update_info_tech(self, request:List[schema.InfoTechUpdate]):
        for req in request:
            total = req.units * req.cost_per_unit
            request_data = req.model_dump()
            request_data["total"] = total
            updated_info_tech = InfoTechBase.model_validate(request_data)
            if updated_info_tech.infotech_id is None:
                return CustomResponse(status="-1", message=Messages.INFO_TECH_UPDATE_NOT)
            TblInfoTech.update_info_tech(updated_info_tech.infotech_id, updated_info_tech,self.db)
        self.db.commit()
        return CustomResponse(status="1", message=Messages.INFO_TECH_UPDATE)
    
    async def delete_info_tech(self, info_tech_delete_id:int):
        deleted_info_tech = TblInfoTech.delete_info_tech(info_tech_delete_id, self.db)
        if not deleted_info_tech:
            return CustomResponse(status="-1", message=Messages.INFO_TECH_UPDATE_NOT)
        return CustomResponse(status="1", message=Messages.INFO_TECH_DELETE)
    
    
