from datetime import datetime
from typing import Optional
import uuid
from src.core.log_conf import logger
from src.db.models.admin import Assignment, Profile
from sqlalchemy.orm import Session

from src.schema.user.profile import ProfileModel


def create_new_profile(new_profile: ProfileModel, db: Session) -> Profile:
    logger.info(f"create MediaActor with url {new_profile.username}")
    profile: Profile = Profile()
    profile.id = str(uuid.uuid4())
    profile.user_name = new_profile.username
    profile.first_name = new_profile.first_name
    profile.last_name = new_profile.last_name
    profile.created_date = datetime.now()
    profile.last_modified_date = datetime.now()
    profile.version = 0
    db.add(profile)
    db.commit()
    db.refresh(profile)
    logger.info(f"created {profile}")
    return profile

def delete_profile(db: Session, profile_id: str):
    logger.info(f"delete Profile with id {profile_id}")
    profile: Optional[Profile] = db.get(Profile, profile_id)
    if profile is not None:
        assignments = profile.assignments
        for assignment in assignments:
            delete_assignment(db, assignment.id)
        db.delete(profile)
        db.commit()

def delete_assignment(db: Session, assignment_id: str) -> None:
    logger.info(f"delete Assignment with id {assignment_id}")
    assignment: Optional[Assignment] = db.get(Assignment, assignment_id)
    if assignment is not None:
        db.delete(assignment)
        db.commit()
