from typing import List
from fastapi import APIRouter, status, HTTPException
from src.core.log_conf import logger
from src.db.models.media import MediaActorFile
from src.db.repository.media.actorfile import delete_mediaactorfile, import_mediaactorfile
from src.db.session import SessionDep
from src.schema.media.actorfile import MediaActorFileModel, MediaActorFileResponse, actorfile_to_response

router = APIRouter()

@router.get("/actorfiles", response_model=List[MediaActorFileResponse])
def get_all_actorfiles(db: SessionDep) -> List[MediaActorFileResponse]:
    results: List[MediaActorFileResponse] = []
    actorfiles = db.query(MediaActorFile).all()
    for media_actorfile in actorfiles:
        response = actorfile_to_response(media_actorfile)
        results.append(response)
    return results

@router.get("/actorfiles/{actorfile_id}", response_model=MediaActorFileResponse)
def get_actorfile(actorfile_id: str, db: SessionDep) -> MediaActorFileResponse:
    media_actorfile = db.get(MediaActorFile, actorfile_id)
    if not media_actorfile:
        raise HTTPException(status_code=404, detail="MediaActor could not be found")
    response = actorfile_to_response(media_actorfile)
    return response

@router.delete("/actorfiles/{actorfile_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_actorfile(actorfile_id: str, db: SessionDep):
    media_actorfile = db.get(MediaActorFile, actorfile_id)
    if not media_actorfile:
        raise HTTPException(status_code=404, detail="MediaActor could not be found")
    delete_mediaactorfile(db, media_actorfile.id)

@router.post("/actorfiles", status_code=status.HTTP_201_CREATED)
def add_actorfile(new_actorfile: MediaActorFileModel, db: SessionDep) -> MediaActorFileResponse:
    logger.info("add actorfile %s - %s", new_actorfile.media_actor_id, new_actorfile.media_file_id)
    try:
        mediaActorFile: MediaActorFile = import_mediaactorfile(db, new_actorfile)
    except Exception as exception:
        raise HTTPException(status_code=409, detail=f"Link duplicate: {exception}")
    response = actorfile_to_response(mediaActorFile)
    return response
