from fastapi import HTTPException, UploadFile

# Maximum Upload Size (10 MB)
MAX_FILE_SIZE = 10 * 1024 * 1024

# Allowed Image Types
ALLOWED_CONTENT_TYPES = [
    "image/jpeg",
    "image/png",
    "image/jpg",
    "image/webp"
]


async def validate_upload(file: UploadFile):

    # --------------------------
    # Check File Type
    # --------------------------

    if file.content_type not in ALLOWED_CONTENT_TYPES:

        raise HTTPException(
            status_code=400,
            detail="Only JPG, JPEG, PNG and WEBP images are allowed."
        )

    # --------------------------
    # Check File Size
    # --------------------------

    contents = await file.read()

    if len(contents) > MAX_FILE_SIZE:

        raise HTTPException(
            status_code=400,
            detail="Maximum upload size is 10 MB."
        )

    # Reset pointer
    await file.seek(0)

    return True