use anyhow::Result;
use async_trait::async_trait;
use reqwest::Client;

use crate::subtitle::types::{DownloadedSubtitle, MediaQuery, ResolvedSubtitle, SubtitleCandidate};
use crate::types::Provider;

#[async_trait]
pub trait SubtitleProvider: Provider {
    fn is_enabled(&self) -> bool;
    fn download_client(&self) -> &Client;

    fn over_daily_limit(&self) -> bool {
        false
    }
    async fn check_alive(&self) -> Result<u64>;
    async fn search(&self, query: &MediaQuery) -> Result<Vec<SubtitleCandidate>>;
    async fn resolve(&self, candidate: &SubtitleCandidate) -> Result<ResolvedSubtitle>;

    async fn download(&self, resolved: &ResolvedSubtitle) -> Result<DownloadedSubtitle> {
        let response = self
            .download_client()
            .get(&resolved.download_url)
            .send()
            .await?
            .error_for_status()?;

        Ok(DownloadedSubtitle {
            header: resolved.header.clone(),
            content: response.bytes().await?.to_vec(),
        })
    }
}
