/*
 * clickhouse-native-rs — Asynchronous ClickHouse client for Rust over the native TCP protocol
 * Copyright (c) 2026 Alexander Panasenko
 *
 * Contact: alex@prod.codes
 * Author: https://prod.codes/about/
 * Project: https://github.com/alex09x/clickhouse-native-rs
 * SPDX-License-Identifier: MIT
 */

//! Interval columns: an `Int64` count per row, the unit in the column type.

use std::sync::Arc;

use chrono_tz::Tz;

use crate::{
    binary::{Encoder, ReadEx},
    errors::Result,
    types::{
        column::{
            column_data::{ArcColumnData, BoxColumnData, ColumnData},
            list::List,
            nullable::NullableColumnData,
            numeric::save_data,
            ColumnFrom, ColumnWrapper,
        },
        Interval, IntervalKind, SqlType, Value, ValueRef,
    },
};

/// A column of `IntervalKind` intervals.
pub(crate) struct IntervalColumnData {
    data: List<i64>,
    kind: IntervalKind,
    /// Whether a value chose the unit; a column made of no values or only
    /// NULLs takes the unit of the table it goes to, until a push.
    unit_known: bool,
}

impl IntervalColumnData {
    pub(crate) fn load<R: ReadEx>(reader: &mut R, kind: IntervalKind, size: usize) -> Result<Self> {
        let mut data = List::zeroed(size);
        reader.read_bytes(data.as_mut())?;
        Ok(IntervalColumnData {
            data,
            kind,
            unit_known: true,
        })
    }

    pub(crate) fn with_capacity(kind: IntervalKind, capacity: usize) -> Self {
        IntervalColumnData {
            data: List::with_capacity(capacity),
            kind,
            unit_known: true,
        }
    }
}

/// The unit of a column of `intervals`: that of the first one, if any.
///
/// # Panics
///
/// When the intervals are of different units: a column has one, and a count
/// of months is not a count of seconds.
fn intervals_kind<'a>(mut intervals: impl Iterator<Item = &'a Interval>) -> Option<IntervalKind> {
    let first = intervals.next()?;
    if let Some(other) = intervals.find(|interval| interval.kind != first.kind) {
        panic!(
            "intervals of different units in one column: {} and {}",
            first.kind, other.kind
        );
    }
    Some(first.kind)
}

impl ColumnFrom for Vec<Interval> {
    fn column_from<W: ColumnWrapper>(source: Self) -> W::Wrapper {
        let kind = intervals_kind(source.iter());
        let data = source.iter().map(|interval| interval.count).collect();
        W::wrap(IntervalColumnData {
            data: List::from_vec(data),
            kind: kind.unwrap_or(IntervalKind::Second),
            unit_known: kind.is_some(),
        })
    }
}

impl ColumnFrom for Vec<Option<Interval>> {
    fn column_from<W: ColumnWrapper>(source: Self) -> W::Wrapper {
        let kind = intervals_kind(source.iter().flatten());
        let nulls = source.iter().map(|v| u8::from(v.is_none())).collect();
        let data = source.iter().map(|v| v.map_or(0, |i| i.count)).collect();
        W::wrap(NullableColumnData {
            nulls,
            inner: Arc::new(IntervalColumnData {
                data: List::from_vec(data),
                kind: kind.unwrap_or(IntervalKind::Second),
                unit_known: kind.is_some(),
            }),
        })
    }
}

impl ColumnData for IntervalColumnData {
    fn sql_type(&self) -> SqlType {
        SqlType::Interval(self.kind)
    }

    fn save(&self, encoder: &mut Encoder, start: usize, end: usize) {
        save_data::<i64>(self.data.as_ref(), encoder, start, end);
    }

    fn len(&self) -> usize {
        self.data.len()
    }

    fn push(&mut self, value: Value) {
        // Block::push checks the unit first and returns an error.
        match value {
            Value::Interval(count, kind) if kind == self.kind => self.data.push(count),
            _ => panic!("{value:?} does not fit into {}", self.sql_type()),
        }
        // A count of this unit, or a NULL placeholder: either way the column
        // no longer takes another unit, so no count is sent as another unit.
        self.unit_known = true;
    }

    fn at(&self, index: usize) -> ValueRef<'_> {
        ValueRef::Interval(self.data.at(index), self.kind)
    }

    fn clone_instance(&self) -> BoxColumnData {
        Box::new(IntervalColumnData {
            data: self.data.clone(),
            kind: self.kind,
            unit_known: self.unit_known,
        })
    }

    /// A column whose unit no value chose takes any unit.
    fn cast_to(&self, _this: &ArcColumnData, target: &SqlType) -> Option<ArcColumnData> {
        match target {
            SqlType::Interval(kind) if !self.unit_known => Some(Arc::new(IntervalColumnData {
                data: self.data.clone(),
                kind: *kind,
                unit_known: true,
            })),
            _ => None,
        }
    }

    fn get_timezone(&self) -> Option<Tz> {
        None
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_a_push_fixes_the_unit() {
        let day = SqlType::Interval(IntervalKind::Day);
        let this: ArcColumnData =
            Arc::new(IntervalColumnData::with_capacity(IntervalKind::Second, 0));
        // As `Vec<Interval>` makes it of no values.
        assert_eq!(intervals_kind([].iter()), None);
        let mut column = IntervalColumnData {
            data: List::with_capacity(1),
            kind: IntervalKind::Second,
            unit_known: false,
        };
        assert!(column.cast_to(&this, &day).is_some());
        column.push(Value::Interval(5, IntervalKind::Second));
        assert!(
            column.cast_to(&this, &day).is_none(),
            "seconds sent as days"
        );
    }
}