# from fastapi import HTTPException, UploadFile
# from PIL import Image
# import io

# MAX_FILE_SIZE = 10 * 1024 * 1024  #10mb

# async def validate_image(file: UploadFile): 
#     content = await file.read()

#     #check empty file
#     if not content: 
#         raise HTTPException(
#             status_code=400,
#             detail="Upload file is empty"
#         )
    
#     #check file size 
#     if len(content) > MAX_FILE_SIZE: 
#         raise HTTPException(
#             status_code=400,
#             detail="File size exceed 10MB"
#         )
    
#     #check valid image
#     try: 
#         image = Image.open(io.BytesIO(content))
#         image.verify()
#     except Exception: 
#         raise HTTPException(
#             status_code=400,
#             detail="Invalid or currupted image file"
#         )
    
#     #reset pointer for later use
#     await file.seek(0)

#     return True


from fastapi import (
    HTTPException,
    UploadFile
)

from PIL import Image

import io


MAX_FILE_SIZE = 10 * 1024 * 1024

ALLOWED_TYPES = [
    "image/png",
    "image/jpeg",
    "image/webp"
]


async def validate_image(
    file: UploadFile
):

    if file.content_type not in ALLOWED_TYPES:

        raise HTTPException(
            status_code=400,
            detail="Unsupported image type"
        )

    content = await file.read()

    if not content:

        raise HTTPException(
            status_code=400,
            detail="Empty file"
        )

    if len(content) > MAX_FILE_SIZE:

        raise HTTPException(
            status_code=400,
            detail="File exceeds 10MB"
        )

    try:

        image = Image.open(
            io.BytesIO(content)
        )

        image.verify()

    except Exception:

        raise HTTPException(
            status_code=400,
            detail="Invalid image file"
        )

    await file.seek(0)

    return True