#![allow(clippy::unwrap_used)]

use lazy_static::lazy_static;
use prometheus::{IntCounter, IntGauge, register_int_counter, register_int_gauge};

lazy_static! {
    pub static ref IMPORT_INTO_INFLIGHT_TASKS: IntGauge = register_int_gauge!(
        "tici_worker_import_into_inflight_tasks",
        "Number of concurrent import-into tasks on this worker"
    )
    .unwrap();
}

lazy_static! {
    pub static ref IMPORT_INTO_ROWS_PROCESSED_TOTAL: IntCounter = register_int_counter!(
        "tici_worker_import_into_rows_processed_total",
        "Total rows processed by import-into on this worker"
    )
    .unwrap();
}

lazy_static! {
    pub static ref IMPORT_INTO_BYTES_PROCESSED_TOTAL: IntCounter = register_int_counter!(
        "tici_worker_import_into_bytes_processed_total",
        "Total bytes processed by import-into on this worker (KV payload: key + value)"
    )
    .unwrap();
}

pub struct ImportIntoInflightGuard;

impl ImportIntoInflightGuard {
    pub fn new() -> Self {
        IMPORT_INTO_INFLIGHT_TASKS.inc();
        Self
    }
}

impl Default for ImportIntoInflightGuard {
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for ImportIntoInflightGuard {
    fn drop(&mut self) {
        IMPORT_INTO_INFLIGHT_TASKS.dec();
    }
}

#[cfg(test)]
mod tests {
    use super::{
        IMPORT_INTO_BYTES_PROCESSED_TOTAL, IMPORT_INTO_INFLIGHT_TASKS,
        IMPORT_INTO_ROWS_PROCESSED_TOTAL, ImportIntoInflightGuard,
    };

    #[test]
    fn test_import_into_inflight_guard() {
        let before = IMPORT_INTO_INFLIGHT_TASKS.get();
        {
            let _guard = ImportIntoInflightGuard::new();
            assert_eq!(IMPORT_INTO_INFLIGHT_TASKS.get(), before + 1);
        }
        assert_eq!(IMPORT_INTO_INFLIGHT_TASKS.get(), before);
    }

    #[test]
    fn test_import_into_rows_counter() {
        let before = IMPORT_INTO_ROWS_PROCESSED_TOTAL.get();
        IMPORT_INTO_ROWS_PROCESSED_TOTAL.inc_by(10);
        assert_eq!(IMPORT_INTO_ROWS_PROCESSED_TOTAL.get(), before + 10);
    }

    #[test]
    fn test_import_into_bytes_counter() {
        let before = IMPORT_INTO_BYTES_PROCESSED_TOTAL.get();
        IMPORT_INTO_BYTES_PROCESSED_TOTAL.inc_by(512);
        assert_eq!(IMPORT_INTO_BYTES_PROCESSED_TOTAL.get(), before + 512);
    }
}
