import uuid
from datetime import datetime
from typing import AnyStr, Optional

from sqlalchemy.orm import Session

from src.core.log_conf import logger
from src.db.models.comic import WorkType
from src.schema.comics.worktype import AddWorkType


def create_new_worktype(work: AddWorkType, db: Session) -> WorkType:
    worktype = WorkType()
    worktype.id = str(uuid.uuid4())
    worktype.created_date = datetime.now()
    worktype.last_modified_date = datetime.now()
    worktype.name = work.worktype
    db.add(worktype)
    db.commit()
    db.refresh(worktype)
    logger.info(f"create_new_worktype: {worktype}")
    return worktype


def update_worktype(work: AddWorkType, worktype_id: AnyStr, db: Session) -> Optional[WorkType]:
    logger.info("update worktype")
    worktype: Optional[WorkType] = db.get(WorkType, worktype_id)
    if worktype is not None:
        worktype.name = work.worktype
        db.add(worktype)
        db.commit()
        db.refresh(worktype)
    return worktype
