use super::{
    Database, DatabaseError,
    entities::{NewSeason, RecentSeasonWithCover, Season, SeasonWithCover, UnmatchedSeason},
    queries,
};
use chrono::Utc;
use rusqlite::params;

impl Database {
    db_query_all!(fn find_seasons_by_show(show_id: i64) -> Vec<Season>, queries::find_seasons_by_show);
    db_query_all!(fn find_unmatched_seasons_with_matched_shows() -> Vec<UnmatchedSeason>, queries::find_unmatched_seasons_with_matched_shows);
    db_query_all!(fn find_recent_seasons_with_covers() -> Vec<RecentSeasonWithCover>, queries::find_recent_seasons_with_covers);
    db_query_all!(fn find_seasons_with_covers(show_id: i64) -> Vec<SeasonWithCover>, queries::find_seasons_with_covers);

    db_query_opt!(fn find_season_by_number(show_id: i64, number: i64) -> Option<Season>, queries::find_season_by_number);

    db_exec!(fn set_season_skip_auto_match(id: i64), queries::set_season_skip_auto_match);
    db_exec!(fn reset_season_auto_match(), queries::reset_season_auto_match);
    //db_exec!(fn set_season_watched(id: i64, watched: bool), queries::set_season_watched);
    //db_exec!(fn set_seasons_watched_by_show(show_id: i64, watched: bool), queries::set_seasons_watched_by_show);
    db_exec!(fn delete_season_images(season_id: i64, image_type: &str), queries::delete_season_images);
    db_exec!(fn link_season_image(season_id: i64, image_id: i64, image_type: &str), queries::link_season_image);

    pub fn delete_empty_seasons(&mut self) -> Result<usize, DatabaseError> {
        let (deleted, _) = self.exec_cmd(&queries::delete_empty_seasons, [])?;
        Ok(deleted)
    }

    pub fn create_season(&mut self, new_season: NewSeason) -> Result<i64, DatabaseError> {
        let now = Utc::now();
        let (_, insert_id) = self.exec_cmd(
            &queries::create_season,
            params![
                new_season.show_id,
                Option::<i64>::None,
                new_season.season_number,
                Option::<String>::None,
                Option::<i64>::None,
                now,
                now
            ],
        )?;

        Ok(insert_id)
    }

    pub fn update_season_tmdb(
        &mut self,
        id: i64,
        tmdb_id: i64,
        title: &str,
        release_year: Option<i64>,
        description: Option<&str>,
        rating: Option<f64>,
    ) -> Result<(), DatabaseError> {
        self.exec_cmd(
            &queries::update_season_tmdb,
            params![tmdb_id, title, release_year, description, rating, id],
        )?;
        Ok(())
    }
}
