use super::{Category, CategoryID, Feed, FeedID};
use crate::schema::{category_mapping, feed_mapping};
use serde::{Deserialize, Serialize};

#[derive(Identifiable, Insertable, Associations, Queryable, Eq, PartialEq, Debug, Hash, Clone, Serialize, Deserialize)]
#[diesel(primary_key(feed_id, category_id))]
#[diesel(table_name = feed_mapping)]
#[diesel(belongs_to(Feed, foreign_key = feed_id))]
#[diesel(check_for_backend(SQLite))]
pub struct FeedMapping {
    pub feed_id: FeedID,
    pub category_id: CategoryID,
    pub sort_index: Option<i32>,
}

//------------------------------------------------------------------

#[derive(Identifiable, Clone, Insertable, Associations, Queryable, Eq, PartialEq, Debug)]
#[diesel(primary_key(category_id))]
#[diesel(table_name = category_mapping)]
#[diesel(belongs_to(Category, foreign_key = category_id))]
#[diesel(check_for_backend(SQLite))]
pub struct CategoryMapping {
    pub parent_id: CategoryID,
    pub category_id: CategoryID,
    pub sort_index: Option<i32>,
}

//------------------------------------------------------------------

pub enum UnifiedMapping {
    Feed(FeedMapping),
    Category(CategoryMapping),
}

impl UnifiedMapping {
    pub fn sort_index(&self) -> Option<i32> {
        match self {
            Self::Feed(f) => f.sort_index,
            Self::Category(c) => c.sort_index,
        }
    }

    pub fn set_sort_index(&mut self, index: i32) {
        match self {
            Self::Feed(f) => f.sort_index = Some(index),
            Self::Category(c) => c.sort_index = Some(index),
        }
    }
}
