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

//! Columns of `Decimal(P, S)` with `P` from 39 to 76 (`Decimal256(S)`): the
//! values as `Int256`, as ClickHouse stores them, and the casts between
//! these and the narrower decimals.

use std::sync::Arc;

use chrono_tz::Tz;
use either::Either;

use crate::{
    binary::{Encoder, ReadEx},
    errors::{Error, Result},
    types::{
        column::{
            column_data::{ArcColumnData, BoxColumnData, ColumnData},
            list::List,
            nullable::NullableColumnData,
            numeric::save_data,
            ArcColumnWrapper, Column, ColumnFrom, ColumnType, ColumnWrapper,
        },
        decimal::NoBits,
        Decimal, Decimal256, Int256, SqlType, Value, ValueRef,
    },
};

pub(crate) struct Decimal256ColumnData {
    pub(crate) data: List<Int256>,
    pub(crate) precision: u8,
    pub(crate) scale: u8,
}

impl Decimal256ColumnData {
    pub(crate) fn load<R: ReadEx>(
        reader: &mut R,
        precision: u8,
        scale: u8,
        size: usize,
    ) -> Result<Self> {
        let mut data = List::zeroed(size);
        reader.read_bytes(data.as_mut())?;
        Ok(Decimal256ColumnData {
            data,
            precision,
            scale,
        })
    }

    pub(crate) fn with_capacity(precision: u8, scale: u8, capacity: usize) -> Self {
        Decimal256ColumnData {
            data: List::with_capacity(capacity),
            precision,
            scale,
        }
    }
}

/// The internal value of a pushed decimal in a column of `precision` and
/// `scale`, or `None` when it has more digits than the column holds there.
pub(crate) fn decimal256_value(value: &Value, precision: u8, scale: u8) -> Option<Int256> {
    if precision > 76 || scale > precision {
        return None;
    }
    let decimal = match value {
        Value::Decimal256(decimal) => *decimal,
        Value::Decimal(decimal) => Decimal256::from(decimal.clone()),
        _ => return None,
    };
    let value = decimal.rescaled(scale)?;
    Decimal256::from_raw(value, precision, scale)
        .fits(precision)
        .then_some(value)
}

/// The column of `values`, which share one scale: precision 76.
fn decimal256_column(values: impl Iterator<Item = Decimal256>, len: usize) -> Decimal256ColumnData {
    let mut data = List::with_capacity(len);
    let mut scale = None;
    for value in values {
        match scale {
            Some(scale) if scale != value.scale() => panic!("scale != scale"),
            _ => scale = Some(value.scale()),
        }
        data.push(value.internal());
    }
    Decimal256ColumnData {
        data,
        precision: 76,
        scale: scale.unwrap_or(4) as u8,
    }
}

impl ColumnFrom for Vec<Decimal256> {
    fn column_from<W: ColumnWrapper>(source: Self) -> W::Wrapper {
        let len = source.len();
        W::wrap(decimal256_column(source.into_iter(), len))
    }
}

impl ColumnFrom for Vec<Option<Decimal256>> {
    fn column_from<W: ColumnWrapper>(source: Self) -> W::Wrapper {
        let nulls = source.iter().map(|v| u8::from(v.is_none())).collect();
        // A NULL takes a zero of the scale the values have.
        let scale = source
            .iter()
            .flatten()
            .next()
            .map_or(4, |v| v.scale() as u8);
        let zero = Decimal256::from_raw(Int256::ZERO, 76, scale);
        let len = source.len();
        let values = source.into_iter().map(|v| v.unwrap_or(zero));
        W::wrap(NullableColumnData {
            nulls,
            inner: Arc::new(decimal256_column(values, len)),
        })
    }
}

impl ColumnData for Decimal256ColumnData {
    fn sql_type(&self) -> SqlType {
        SqlType::Decimal(self.precision, self.scale)
    }

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

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

    fn push(&mut self, value: Value) {
        // Block::push checks this first and returns an error.
        let Some(internal) = decimal256_value(&value, self.precision, self.scale) else {
            panic!("{value} does not fit into {}", self.sql_type());
        };
        self.data.push(internal);
    }

    fn at(&self, index: usize) -> ValueRef<'_> {
        ValueRef::Decimal256(self.data.get(index), self.precision, self.scale)
    }

    fn clone_instance(&self) -> BoxColumnData {
        Box::new(Self {
            data: self.data.clone(),
            precision: self.precision,
            scale: self.scale,
        })
    }

    /// A cast inside an array or a map, value by value as at the top.
    fn cast_to(&self, _this: &ArcColumnData, target: &SqlType) -> Option<ArcColumnData> {
        cast_decimal_column(self, target)
    }

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

/// A decimal `value` brought to a decimal column of `precision` and
/// `scale`, or `None` when it does not fit there.
fn cast_decimal(value: Value, precision: u8, scale: u8) -> Option<Value> {
    let internal = decimal256_value(&value, precision, scale)?;
    if precision > 38 {
        return Some(Value::Decimal256(Decimal256::from_raw(
            internal, precision, scale,
        )));
    }
    let internal = i128::try_from(internal).ok()?;
    let nobits = NoBits::from_precision(precision)?;
    Some(Value::Decimal(Decimal::from_raw(
        internal, precision, scale, nobits,
    )))
}

/// Casts the decimals of `column` to the decimal `target` value by value, or
/// `None` when one does not fit: the casts of decimals nested in arrays and
/// maps, where the column cannot report an error of its own.
pub(crate) fn cast_decimal_column(
    column: &(dyn ColumnData + Send + Sync),
    target: &SqlType,
) -> Option<ArcColumnData> {
    let SqlType::Decimal(precision, scale) = *target else {
        return None;
    };
    let mut cast =
        <dyn ColumnData>::from_type::<ArcColumnWrapper>(target.clone(), Tz::Zulu, column.len())
            .ok()?;
    let data = Arc::get_mut(&mut cast)?;
    for index in 0..column.len() {
        data.push(cast_decimal(
            Value::from(column.at(index)),
            precision,
            scale,
        )?);
    }
    Some(cast)
}

/// Casts a decimal `column` to `dst_type` (a decimal or a nullable one) when
/// one of them is a Decimal256: value by value, each brought to the target's
/// scale and checked against its precision.
pub(crate) fn cast_decimal256<K: ColumnType>(
    column: &Column<K>,
    dst_type: &SqlType,
) -> Result<ArcColumnData> {
    let (precision, scale) = match dst_type {
        SqlType::Decimal(precision, scale) => (*precision, *scale),
        SqlType::Nullable(SqlType::Decimal(precision, scale)) => (*precision, *scale),
        _ => unreachable!("cast_decimal256 is called for decimal types"),
    };
    let mut target =
        <dyn ColumnData>::from_type::<ArcColumnWrapper>(dst_type.clone(), Tz::Zulu, column.len())?;
    let data = Arc::get_mut(&mut target).expect("a new column is not shared");
    for index in 0..column.len() {
        let value = Value::from(column.at(index));
        let cast = match value {
            // A NULL takes the target's type, whose default the column stores.
            Value::Nullable(Either::Left(_)) => Some(Value::Nullable(Either::Left(
                SqlType::Decimal(precision, scale).into(),
            ))),
            Value::Nullable(Either::Right(inner)) => cast_decimal(*inner, precision, scale)
                .map(|inner| Value::Nullable(Either::Right(Box::new(inner)))),
            value => cast_decimal(value, precision, scale),
        };
        let Some(cast) = cast else {
            return Err(Error::Other(
                format!(
                    "the value {} of column `{}` does not fit into {dst_type}",
                    column.at(index),
                    column.name()
                )
                .into(),
            ));
        };
        data.push(cast);
    }
    Ok(target)
}