use rand::{distributions::Uniform, prelude::Distribution, thread_rng};
use regex::Regex;

use crate::db::{doll, schema::DollTagsDb};

pub fn generate_ids() -> Vec<i32> {
	let uniform = Uniform::new_inclusive::<i32, i32>(100_000, 999_999);
	let mut rng = thread_rng();
	(1..=10).map(|_| uniform.sample(&mut rng)).collect()
}

pub async fn pick_ids(mut db: DollTagsDb) -> Result<Vec<i32>, sqlx::Error> {
	let mut ids_bundle = generate_ids();
	let occupied_ids = doll::check_ids(&mut *db, &ids_bundle).await?;
	ids_bundle.retain(|&id| !occupied_ids.contains(&id));
	Ok(ids_bundle.iter().take(5).map(|v| *v).collect::<Vec<i32>>())
}

pub fn id_public_to_db(id: &str) -> Option<i32> {
	let id_re = Regex::new(r"^\d{6}$").unwrap();

	if id_re.is_match(id) {
		id.parse::<i32>().ok()
	} else {
		None
	}
}
pub fn id_db_to_public(id: i32) -> String {
	let first = id / 1000;
	let second = id % 1000;
	format!("{:0>3}-{:0>3}", first, second)
}
