// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Path constants for table engines, cluster states and WAL
//! All paths relative to data_home(file storage) or root path(S3, OSS etc).

use crate::storage::{RegionId, RegionSeq, TableId};

/// WAL dir for local file storage
pub const WAL_DIR: &str = "wal";

/// Data dir for table engines
pub const DATA_DIR: &str = "data/";

/// Cluster state dir
pub const CLUSTER_DIR: &str = "cluster/";

/// Generate region name in the form of "{TABLE_ID}_{REGION_SEQUENCE}"
#[inline]
pub fn region_name(table_id: TableId, region_sequence: RegionSeq) -> String {
    format!("{table_id}_{region_sequence:010}")
}

#[inline]
pub fn table_dir(path: &str, table_id: TableId) -> String {
    format!("{DATA_DIR}{path}/{table_id}/")
}

pub fn region_dir(path: &str, region_id: RegionId) -> String {
    format!(
        "{}{}/",
        table_dir(path, region_id.table_id()),
        region_name(region_id.table_id(), region_id.region_sequence())
    )
}

/// get_storage_path returns the storage path from the region_dir.
///
/// It will always return the storage path if the region_dir is valid, otherwise None.
/// The storage path is constructed from the catalog and schema, which are generated by `common_meta::ddl::utils::region_storage_path`.
/// We can extract the catalog and schema from the region_dir by following example:
/// ```
/// use common_meta::ddl::utils::get_catalog_and_schema;
///
/// fn catalog_and_schema(region_dir: &str, region_id: RegionId) -> Option<(String, String)> {
///     get_catalog_and_schema(&get_storage_path(region_dir, region_id)?)
/// }
/// ```
pub fn get_storage_path(region_dir: &str, region_id: RegionId) -> Option<String> {
    if !region_dir.starts_with(DATA_DIR) {
        return None;
    }

    // For example, if region_dir is "data/my_catalog/my_schema/42/42_0000000001/", the parts will be '42/42_0000000001'.
    let parts = format!(
        "{}/{}",
        region_id.table_id(),
        region_name(region_id.table_id(), region_id.region_sequence())
    );

    // Ignore the last '/'. The original path will be like "${DATA_DIR}${catalog}/${schema}".
    let pos = region_dir.rfind(&parts)? - 1;

    if pos < DATA_DIR.len() {
        return None;
    }

    Some(region_dir[DATA_DIR.len()..pos].to_string())
}

#[cfg(test)]
mod tests {
    use common_meta::ddl::utils::{get_catalog_and_schema, region_storage_path};

    use super::*;

    fn catalog_and_schema(region_dir: &str, region_id: RegionId) -> Option<(String, String)> {
        get_catalog_and_schema(&get_storage_path(region_dir, region_id)?)
    }

    #[test]
    fn test_region_dir() {
        let region_id = RegionId::new(42, 1);
        assert_eq!(
            region_dir("my_catalog/my_schema", region_id),
            "data/my_catalog/my_schema/42/42_0000000001/"
        );
    }

    #[test]
    fn test_get_catalog_and_schema_from_region_dir() {
        let tests = [
            (RegionId::new(42, 1), "my_catalog", "my_schema"),
            (RegionId::new(1234, 1), "my_catalog_1234", "my_schema_1234"),
            (RegionId::new(5678, 1), "my_catalog_5678", "my_schema"),
            (RegionId::new(5678, 1), "my_catalog", "my_schema_5678"),
        ];

        for (region_id, test_catalog, test_schema) in tests.iter() {
            let region_dir = region_dir(
                region_storage_path(test_catalog, test_schema).as_str(),
                *region_id,
            );
            let (catalog, schema) = catalog_and_schema(&region_dir, *region_id).unwrap();
            assert_eq!(catalog, *test_catalog);
            assert_eq!(schema, *test_schema);
        }
    }

    #[test]
    fn test_get_catalog_and_schema_from_invalid_region_dir() {
        assert_eq!(
            catalog_and_schema("invalid_data", RegionId::new(42, 1)),
            None
        );
    }
}
