"""Brand."""
import os
import shutil

from fastapi import HTTPException, UploadFile
from sqlalchemy.orm import Session

from app.api.brand.schemas import BrandCreate, BrandUpdate
from app.dependency.authantication import JWTPayloadSchema
from app.models.main.brand import BrandBase, TblBrand
from app.utils.schemas_utils import CustomResponse


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

    async def create_brand(self, brand_data: BrandCreate, brand_image: UploadFile):
        if not brand_image:
            return CustomResponse(status="0", message="Brand image is required")
        image_filename = brand_image.filename
        image_path = f"uploads/{image_filename}"
        
        with open(image_path, "wb") as buffer:
            shutil.copyfileobj(brand_image.file, buffer)
        create_data=BrandBase.model_validate(brand_data)
        TblBrand.create(create_data,self.db)
        self.db.commit()
        return CustomResponse(status="1", message="Brand created successfully", data={"image_url": image_path})
    
    async def update_brand(self, brand_id: int, brand_data: BrandUpdate, brand_image: UploadFile):
        brand = self.db.query(TblBrand).filter(TblBrand.brand_id == brand_id).first()
        if not brand:
            return CustomResponse(status="0", message="Brand not found")
        if brand_data.brand_name is not None:
            brand.brand_name = brand_data.brand_name
        if brand_data.rationale is not None:
            brand.rationale = brand_data.rationale
        if brand_image:
            image_filename = brand_image.filename
            image_path = f"uploads/{image_filename}"
            with open(image_path, "wb") as buffer:
                shutil.copyfileobj(brand_image.file, buffer)
            if os.path.exists(brand.brand_image):
                os.remove(brand.brand_image)
            brand.brand_image = image_path
        self.db.commit()
        self.db.refresh(brand)
        return CustomResponse(status="1", message="Brand updated successfully", data={"image_url": brand.brand_image})
    
    async def get_brand_by_id(self, brand_id: int):
        brand = self.db.query(TblBrand).filter(TblBrand.brand_id == brand_id).first()
        if not brand:
            raise HTTPException(status_code=404, detail="Brand not found")
        return brand
    
    async def get_brands_by_group_id(self, group_id: int):
        brands = self.db.query(TblBrand).filter(TblBrand.group_id == group_id).all()
        if not brands:
            raise HTTPException(status_code=404, detail="No brands found for this group")
        return brands


    async def delete_brand(self, brand_id: int):
        deleted = TblBrand.delete(brand_id, self.db)
        if not deleted:
            return CustomResponse(status="-1", message="Brand not found")
        return CustomResponse(status="1", message="Brand deleted successfully")

# import base64
# import os
# from datetime import datetime
# from sqlalchemy.orm import Session
# from app.api.brand import schemas
# from app.models.main.brand import BrandBase, TblBrand
# from app.utils.schemas_utils import CustomResponse

# UPLOAD_DIR = "uploads"
# os.makedirs(UPLOAD_DIR, exist_ok=True)

# class BrandService:
#     def __init__(self, db: Session):
#         self.db = db

#     def save_base64_image(self, base64_string: str, brand_name: str) -> str:
#         """Converts Base64 to an image file and returns the file path."""
#         try:
#             image_data = base64.b64decode(base64_string)
#             timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
#             filename = f"{brand_name.replace(' ', '_')}_{timestamp}.png"
#             file_path = os.path.join(UPLOAD_DIR, filename)

#             with open(file_path, "wb") as image_file:
#                 image_file.write(image_data)

#             return file_path
#         except Exception as e:
#             print(f"Error saving image: {e}")
#             return None

#     def create_brand(self, brand_name: str, rationale: str, base64_image: str) -> CustomResponse:
#         """Creates a brand with an image saved from Base64."""
#         if not base64_image:
#             return CustomResponse(status="0", message="Brand image is required")

#         image_path = self.save_base64_image(base64_image, brand_name)
#         if not image_path:
#             return CustomResponse(status="0", message="Error saving image")

#         new_brand = TblBrand(brand_name=brand_name, rationale=rationale, brand_image=image_path)
#         self.db.add(new_brand)
#         self.db.commit()
#         self.db.refresh(new_brand)

#         return CustomResponse(status="1", message="Brand created successfully", data={"image_url": image_path})

#     async def update_brand(self, request: schemas.BrandUpdate):
#         updated_brand = BrandBase.model_validate(request)  # Validate and create updated user model
#         if updated_brand .brand_id is None:
#             return CustomResponse(status="-1", message="User id not found")  # Return error if user ID is missing
#         TblBrand.update(updated_brand .brand_id,updated_brand, self.db)  # Update user in the database
#         self.db.commit()  # Commit the transaction
#         return CustomResponse(status="1", message="User updated successfully")  # Return success response


