/*
 * 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
 */

//! Rust tuples of up to 12 elements and ClickHouse `Tuple` values: reading
//! (`FromSql` for `(A, B, ...)` and `Vec<(A, B, ...)>`), building rows
//! (`Value: From<(A, B, ...)>`) and building columns to insert
//! (`ColumnFrom for Vec<(A, B, ...)>`).

use std::sync::Arc;

use crate::{
    errors::{Error, FromSqlError},
    types::{
        column::{tuple::TupleColumnData, ArcColumnWrapper, ColumnFrom, ColumnWrapper},
        from_sql::{FromSql, FromSqlResult},
        SqlType, Value, ValueRef,
    },
};

fn not_a_tuple(value: ValueRef<'_>, len: usize) -> Error {
    Error::FromSql(FromSqlError::InvalidType {
        src: SqlType::from(value).to_string(),
        dst: format!("a tuple of {len} elements").into(),
    })
}

fn not_an_array_of_tuples(value: ValueRef<'_>, len: usize) -> Error {
    Error::FromSql(FromSqlError::InvalidType {
        src: SqlType::from(value).to_string(),
        dst: format!("arrays of tuples of {len} elements").into(),
    })
}

macro_rules! tuple_impls {
    ( $( $len:literal: ( $( $t:ident $v:ident $i:tt ),+ ) )+ ) => {
        $(
            impl<'a, $( $t: FromSql<'a> ),+> FromSql<'a> for ( $( $t, )+ ) {
                fn from_sql(value: ValueRef<'a>) -> FromSqlResult<Self> {
                    match value {
                        ValueRef::Tuple(values) if values.len() == $len => {
                            Ok(( $( $t::from_sql(values[$i].clone())?, )+ ))
                        }
                        _ => Err(not_a_tuple(value, $len)),
                    }
                }
            }

            impl<'a, $( $t: FromSql<'a> ),+> FromSql<'a> for Vec<( $( $t, )+ )> {
                fn from_sql(value: ValueRef<'a>) -> FromSqlResult<Self> {
                    match value {
                        ValueRef::Array(SqlType::Tuple(elements), values) if elements.len() == $len => values
                            .iter()
                            .map(|value| <( $( $t, )+ )>::from_sql(value.clone()))
                            .collect(),
                        _ => Err(not_an_array_of_tuples(value, $len)),
                    }
                }
            }

            // Arrays of arrays of tuples, as Polygon and MultiLineString are.
            impl<'a, $( $t: FromSql<'a> ),+> FromSql<'a> for Vec<Vec<( $( $t, )+ )>> {
                fn from_sql(value: ValueRef<'a>) -> FromSqlResult<Self> {
                    match value {
                        ValueRef::Array(SqlType::Array(SqlType::Tuple(elements)), values)
                            if elements.len() == $len =>
                        {
                            values
                                .iter()
                                .map(|value| Vec::<( $( $t, )+ )>::from_sql(value.clone()))
                                .collect()
                        }
                        _ => Err(not_an_array_of_tuples(value, $len)),
                    }
                }
            }

            // Three levels, as MultiPolygon is.
            impl<'a, $( $t: FromSql<'a> ),+> FromSql<'a> for Vec<Vec<Vec<( $( $t, )+ )>>> {
                fn from_sql(value: ValueRef<'a>) -> FromSqlResult<Self> {
                    match value {
                        ValueRef::Array(
                            SqlType::Array(SqlType::Array(SqlType::Tuple(elements))),
                            values,
                        ) if elements.len() == $len => values
                            .iter()
                            .map(|value| Vec::<Vec<( $( $t, )+ )>>::from_sql(value.clone()))
                            .collect(),
                        _ => Err(not_an_array_of_tuples(value, $len)),
                    }
                }
            }

            impl<$( $t ),+> From<( $( $t, )+ )> for Value
            where
                $( Value: From<$t>, )+
            {
                fn from(value: ( $( $t, )+ )) -> Value {
                    Value::Tuple(Arc::new(vec![ $( Value::from(value.$i) ),+ ]))
                }
            }

            impl<$( $t ),+> ColumnFrom for Vec<( $( $t, )+ )>
            where
                $( Vec<$t>: ColumnFrom, )+
            {
                fn column_from<W: ColumnWrapper>(source: Self) -> W::Wrapper {
                    $( let mut $v: Vec<$t> = Vec::with_capacity(source.len()); )+
                    for row in source {
                        $( $v.push(row.$i); )+
                    }
                    W::wrap(TupleColumnData {
                        elements: vec![ $( ColumnFrom::column_from::<ArcColumnWrapper>($v) ),+ ],
                        names: vec![None; $len],
                    })
                }
            }
        )+
    };
}

tuple_impls! {
    1: (A a 0)
    2: (A a 0, B b 1)
    3: (A a 0, B b 1, C c 2)
    4: (A a 0, B b 1, C c 2, D d 3)
    5: (A a 0, B b 1, C c 2, D d 3, E e 4)
    6: (A a 0, B b 1, C c 2, D d 3, E e 4, F f 5)
    7: (A a 0, B b 1, C c 2, D d 3, E e 4, F f 5, G g 6)
    8: (A a 0, B b 1, C c 2, D d 3, E e 4, F f 5, G g 6, H h 7)
    9: (A a 0, B b 1, C c 2, D d 3, E e 4, F f 5, G g 6, H h 7, I i 8)
    10: (A a 0, B b 1, C c 2, D d 3, E e 4, F f 5, G g 6, H h 7, I i 8, J j 9)
    11: (A a 0, B b 1, C c 2, D d 3, E e 4, F f 5, G g 6, H h 7, I i 8, J j 9, K k 10)
    12: (A a 0, B b 1, C c 2, D d 3, E e 4, F f 5, G g 6, H h 7, I i 8, J j 9, K k 10, L l 11)
}

#[cfg(test)]
mod test {
    use crate::types::{Block, Simple, SqlType};

    #[test]
    fn test_tuple_column_from_rust_tuples() {
        let block = Block::<Simple>::new()
            .column("t", vec![(1_u8, "a"), (2, "b")])
            .column("n", vec![(Some(1_u32), 1.5_f64, -1_i64), (None, 2.5, -2)]);
        assert_eq!(
            block.get_column("t").unwrap().sql_type(),
            SqlType::Tuple(vec![(None, &SqlType::UInt8), (None, &SqlType::String)])
        );
        let t: (u8, String) = block.get(1, "t").unwrap();
        assert_eq!(t, (2, "b".to_string()));
        let n: (Option<u32>, f64, i64) = block.get(1, "n").unwrap();
        assert_eq!(n, (None, 2.5, -2));
        // The arity has to match.
        assert!(block.get::<(u8, String, u8), _>(0, "t").is_err());
        assert_eq!(
            block.get_column("n").unwrap().sql_type().to_string(),
            "Tuple(Nullable(UInt32), Float64, Int64)"
        );
    }

    #[test]
    fn test_rows_of_tuples() {
        use std::{collections::HashSet, sync::Arc};

        use crate::{
            row,
            types::{FromSql, Value, ValueRef},
        };

        let block = Block::<Simple>::new().column("t", vec![(1_u8, "a")]);
        // A push into a clone copies the shared element columns first.
        let mut copy = block.clone();
        copy.push(row! { t: (2_u8, "b") }).unwrap();
        assert_eq!((block.row_count(), copy.row_count()), (1, 2));

        // A tuple of another arity, or an empty one, is an error, not a panic.
        assert!(copy.push(row! { t: (3_u8, "c", 4_u8) }).is_err());
        assert!(copy.push(row! { t: 5_u8 }).is_err());
        let mut empty = Block::<Simple>::new();
        let row = vec![("t".to_string(), Value::Tuple(Arc::new(Vec::new())))];
        assert!(empty.push(row).is_err());
        assert_eq!((copy.row_count(), empty.row_count()), (2, 0));

        // An empty array of another type is not an array of these tuples.
        let empty_bytes = ValueRef::Array(&SqlType::UInt8, Arc::new(Vec::new()));
        assert!(Vec::<(u8, u8)>::from_sql(empty_bytes).is_err());

        // Tuples of any element type hash, as map keys need.
        let keys: HashSet<Value> = [
            Value::from((Value::Date(1), 1_u8)),
            Value::from((Value::Date(2), 1_u8)),
        ]
        .into_iter()
        .collect();
        assert_eq!(keys.len(), 2);
    }

    #[test]
    fn test_tuple_values_compare_and_hash_by_their_elements() {
        use std::{
            collections::{hash_map::DefaultHasher, HashMap},
            hash::{Hash, Hasher},
        };

        use crate::types::{Decimal, Value};

        fn hash(value: &Value) -> u64 {
            let mut hasher = DefaultHasher::new();
            value.hash(&mut hasher);
            hasher.finish()
        }

        // 2.0 and 2.00 are equal, so they hash alike.
        let two = Value::from((Decimal::new(20, 1),));
        let two_again = Value::from((Decimal::new(200, 2),));
        assert_eq!(two, two_again);
        assert_eq!(hash(&two), hash(&two_again));
        assert_ne!(hash(&two), hash(&Value::from((Decimal::new(21, 1),))));

        // Tuples holding maps compare the maps.
        let map = || Value::from(HashMap::from([(1_u8, 2_u8)]));
        assert_eq!(Value::from((map(), 1_u8)), Value::from((map(), 1_u8)));

        // DateTime64 ticks in 2290 compare without overflowing.
        let tz = chrono_tz::UTC;
        let late = 10_098_259_200_000_i64; // 2290-01-01 in milliseconds
        assert_eq!(
            Value::from((Value::DateTime64(late, (3, tz)),)),
            Value::from((Value::DateTime64(late, (3, tz)),))
        );
    }

    #[test]
    fn test_named_tuple_type_name() {
        let named = SqlType::Tuple(vec![
            (Some("a".into()), &SqlType::UInt8),
            (Some("b c".into()), &SqlType::String),
        ]);
        assert_eq!(named.to_string(), "Tuple(a UInt8, `b c` String)");
    }
}