import uuid
from typing import Any, Annotated, Optional
from app.utils import validate_file_size_type, save_picture, del_picture
from fastapi import APIRouter, HTTPException, UploadFile, File, Form
from sqlmodel import func, select

from app.api.deps import CurrentUser, SessionDep
from app.models import (
    AboutUsBase,
    AboutUs,
    AboutUsPublic,
    AboutUsCreate,
    AboutsUpdate,
    AboutsListPublic,
    Message,
)

router = APIRouter()


@router.post("/", response_model=AboutUsPublic)
async def create_aboutUs(
    *,
    session: SessionDep,
    current_user: CurrentUser,
    description: str = Form(),
    title: str = Form(),
    image: Annotated[UploadFile, File()],
    index: int = Form()
) -> Any:
    """
    Create new about us.
    """
    validate_file_size_type(image)
    imageUrl = await save_picture(file=image, folder_name="tmp")
    # aboutus_in.image = imageUrl
    aboutUs_in = AboutUsCreate(description=description, image=imageUrl, index=index ,title=title)
    aboutUs = AboutUs.from_orm(aboutUs_in)
    session.add(aboutUs)
    session.commit()
    session.refresh(aboutUs)
    return aboutUs


@router.put("/{id}", response_model=AboutUsPublic)
async def edit_aboutUs(
    *,
    session: SessionDep,
    current_user: CurrentUser,
    id: uuid.UUID,
    description: str = Form(),
    image: Annotated[UploadFile, File()] = None,
    title: str = Form(),
    index: int = Form()
) -> Any:
    aboutUs = session.get(AboutUs, id)
    
    if image is not None:
        validate_file_size_type(image)
        imageUrl = await save_picture(file=image, folder_name="tmp")
        await del_picture(aboutUs.image)
        aboutUs_in = AboutsUpdate(description=description, image=imageUrl, index=index, title=title)
    else :
        aboutUs_in = AboutsUpdate(description=description, image=aboutUs.image, index=index, title=title)

    update_dict = aboutUs_in.model_dump(exclude_unset=True)
    aboutUs.sqlmodel_update(update_dict)
    session.add(aboutUs)
    session.commit()
    session.refresh(aboutUs)
    
    return aboutUs


@router.get("/", response_model=AboutsListPublic)
def read_aboutus_list(session: SessionDep, skip: int = 0, limit: int = 100) -> Any:

    count_statement = select(func.count()).select_from(AboutUs)
    count = session.exec(count_statement).one()
    statement = select(AboutUs).offset(skip).limit(limit)
    aboutus = session.exec(statement).all()

    return AboutsListPublic(data=aboutus, count=count)


@router.delete("/{id}")
async def delete_aboutus(
    session: SessionDep, current_user: CurrentUser, id: uuid.UUID
) -> Message:
    """
    Delete an course.
    """
    aboutUs = session.get(AboutUs, id)
    if not aboutUs:
        raise HTTPException(status_code=404, detail="aboutUs not found")
    await del_picture(aboutUs.image)
    session.delete(aboutUs)
    session.commit()
    return Message(message="aboutUs deleted successfully")
