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 (
   Organ,
   OrganPublic,
   OrganCreate,
   OrganUpdate,
   OrganListPublic,
   Message
)

router = APIRouter()


@router.post("/", response_model=OrganPublic)
async def create_organ(
    *,
    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
    organ_in = OrganCreate(description=description, image=imageUrl, index=index ,title=title)
    organ = Organ.from_orm(organ_in)
    session.add(organ)
    session.commit()
    session.refresh(organ)
    return organ


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

    update_dict = organ_in.model_dump(exclude_unset=True)
    organ.sqlmodel_update(update_dict)
    session.add(organ)
    session.commit()
    session.refresh(organ)
    
    return organ


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

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

    return OrganListPublic(data=organ, count=count)


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