use color_eyre::eyre::{Context, Result};
use serde::Deserialize;
use url::Url;

use crate::settings::TheMovieDb;

pub type TMDbId = u64;

pub async fn poster_url(settings: &TheMovieDb, id: TMDbId) -> Result<Url> {
    let result = reqwest::get(format!(
        "https://api.themoviedb.org/3/movie/{}?api_key={}&language={}",
        id, settings.api_key, settings.language
    ))
    .await
    .wrap_err("Failed to access the movie database.")?;

    #[derive(Deserialize, Debug, Clone)]
    struct TMDbMovie {
        poster_path: String,
    }
    let movie = result
        .json::<TMDbMovie>()
        .await
        .wrap_err("Failed to exract json data.")?;

    let tmdb_url = Url::parse("https://image.tmdb.org").wrap_err("")?;

    tmdb_url
        .join(&format!("t/p/w500{}", movie.poster_path))
        .wrap_err("")
}
