use crate::{
    codec::{TABLE_KEY_LEN, codec_v2::KEYSPACE_PREFIX_LEN},
    keyspace::NULLSPACEID,
};

// Represent a unique key to an index in TiCI
#[derive(Default, Hash, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct IndexKey {
    pub keyspace_id: u32,
    pub table_id: i64,
    pub index_id: i64,
}

impl IndexKey {
    pub fn new_nullspace(table_id: i64, index_id: i64) -> Self {
        Self {
            keyspace_id: NULLSPACEID,
            table_id,
            index_id,
        }
    }

    pub fn new(keyspace_id: u32, table_id: i64, index_id: i64) -> Self {
        Self {
            keyspace_id,
            table_id,
            index_id,
        }
    }

    pub fn to_s3_prefix(&self) -> String {
        crate::s3_keys::index_key(self.keyspace_id, self.table_id, self.index_id)
    }

    pub fn is_tidb_x(&self) -> bool {
        self.keyspace_id != NULLSPACEID
    }

    pub fn trim_prefix(&self, v: &[u8]) -> Vec<u8> {
        if self.is_tidb_x() {
            v[KEYSPACE_PREFIX_LEN + TABLE_KEY_LEN..].to_vec()
        } else {
            v[TABLE_KEY_LEN..].to_vec()
        }
    }
}

impl std::fmt::Debug for IndexKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "(keyspace_id={}/table_id={}/index_id={})",
            self.keyspace_id, self.table_id, self.index_id
        ))
    }
}
