use crate::model::{PackType, PackingContext};
use chrono::{DateTime, Utc};
use magnetar_model::ck;
use magnetar_sdk::types::note::{PollBase, PollChoice};

pub type PollPackInput<'a> = (&'a ck::poll::Model, Option<&'a [ck::poll_vote::Model]>);

impl PackType<PollPackInput<'_>> for PollBase {
    fn extract(_context: &PackingContext, (poll, votes): PollPackInput<'_>) -> Self {
        PollBase {
            expires_at: poll.expires_at.map(DateTime::<Utc>::from),
            expired: poll.expires_at.is_some_and(|e| e < Utc::now()),
            multiple_choice: poll.multiple,
            options: poll
                .choices
                .iter()
                .zip(poll.votes.iter())
                .enumerate()
                .map(|(i, (name, count))| PollChoice {
                    title: name.to_string(),
                    votes_count: *count as usize,
                    voted: votes.map(|v| v.iter().any(|v| v.choice as usize == i)),
                })
                .collect(),
        }
    }
}
