from typing import List

from fastapi import APIRouter, status, HTTPException
from src.core.log_conf import logger
from src.db.repository.media.actor import delete_mediaactor, import_mediaactor
from src.db.session import SessionDep
from src.schema.media.actor import MediaActorModel, MediaActorResponse, actor_to_response
from src.db.models.media import MediaActor

router = APIRouter()

@router.get("/actors", response_model=List[MediaActorResponse])
def get_all_actors(db: SessionDep) -> List[MediaActorResponse]:
    results: list[MediaActorResponse] = []
    actors = db.query(MediaActor).all()
    for mediaactor in actors:
        response =  actor_to_response(mediaactor)
        results.append(response)
    return results

@router.get("/actors/{actor_id}", response_model=MediaActorResponse)
def get_actor(actor_id: str, db: SessionDep) -> MediaActorResponse:
    media_actor = db.get(MediaActor, actor_id)
    if not media_actor:
        raise HTTPException(status_code=404, detail="MediaActor could not be found")
    response = actor_to_response(media_actor)
    return response

@router.delete("/actors/{actor_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_actor(actor_id: str, db: SessionDep):
    media_actor = db.get(MediaActor, actor_id)
    if not media_actor:
        raise HTTPException(status_code=404, detail="MediaActor could not be found")
    logger.info(f"delete MediaActor: {actor_id}")
    delete_mediaactor(db, media_actor.id)

@router.post("/actors", status_code=status.HTTP_201_CREATED)
def add_actor(new_actor: MediaActorModel, db: SessionDep) -> MediaActorResponse:
    logger.info(f"add actor {new_actor.url}")
    try:
        mediaActor: MediaActor = import_mediaactor(db, new_actor)
    except Exception as exception:
        raise HTTPException(status_code=409, detail=f"Link duplicate: {exception}")
    response = actor_to_response(mediaActor)
    return response
