from typing import List

from fastapi import APIRouter, HTTPException, status

from src.db.models.comic import Artist
from src.db.repository.comics.artist import get_artist_details
from src.db.session import SessionDep
from src.schema.comics.artist import ArtistCreation, ArtistResponse, artist_to_response
from src.schema.comics.artist_details import ArtistDetailResponse


router = APIRouter()


@router.get("/artists", response_model=List[ArtistResponse])
def get_all_artists(db: SessionDep) -> List[ArtistResponse]:
    results: List[ArtistResponse] = []
    artists = db.query(Artist).all()
    for artist in artists:
        response = artist_to_response(artist)
        results.append(response)
    return results


@router.get("/artists/{artist_id}", response_model=ArtistResponse)
def get_artist(artist_id: str, db: SessionDep) -> ArtistResponse:
    artist = db.get(Artist, artist_id)
    if artist is None:
        raise HTTPException(status_code=404, detail="Artist could not be found")
    response: ArtistResponse = artist_to_response(artist)
    return response


@router.get("/artists/details/{artist_id}", response_model=ArtistDetailResponse)
def get_artist_details_by_id(artist_id: str, db: SessionDep) -> ArtistDetailResponse:
    artist = db.get(Artist, artist_id)
    if artist is None:
        raise HTTPException(status_code=404, detail="Artist could not be found")
    response: ArtistDetailResponse = get_artist_details(artist)
    return response


@router.post("/artists", status_code=status.HTTP_201_CREATED)
def add_artist(db: SessionDep, artist_creation: ArtistCreation) -> ArtistResponse:
    artist: Artist = Artist()
    setattr(artist, "name", artist_creation.name)
    try:
        db.add(artist)
        db.commit()
    except:
        raise HTTPException(status_code=409, detail="Artist already added")
    response = artist_to_response(artist)
    return response
