use crate::models::game::mail_history_info::MailHistoryInfo;
use serde_json::Value;
use sqlx::SqlitePool;
/// Insert a full JSON array of MailHistoryInfo records for a UID.
pub async fn insert_mail_history_info(
    pool: &SqlitePool,
    data: &Value,
    uid: i64,
) -> sqlx::Result<()> {
    let arr = match data.get("mailHistoryInfo").and_then(|v| v.as_array()) {
        Some(a) => a,
        None => {
            eprintln!("insert_mail_history_info: missing or invalid 'mailHistoryInfo' array");
            return Ok(());
        }
    };

    for entry in arr {
        // Handle repeated nested MailInfo - extract InvenIndex values
        let mail_info_index =
            if let Some(nested_arr) = entry.get("mailInfo").and_then(|v| v.as_array()) {
                let index: Vec<i64> = nested_arr
                    .iter()
                    .filter_map(|item| item.get("invenIndex").and_then(|v| v.as_i64()))
                    .collect();

                if index.is_empty() {
                    None
                } else {
                    Some(serde_json::to_string(&index).unwrap())
                }
            } else {
                None
            };
        let total_count = entry
            .get("totalCount")
            .and_then(|v| v.as_i64())
            .unwrap_or_default() as i32;

        sqlx::query(
            r#"
INSERT INTO MailHistoryInfo (
    Uid,
    MailInfoIndex,
    TotalCount
) VALUES (
    ?,
    ?,
    ?
)
"#,
        )
        .bind(uid)
        .bind(&mail_info_index)
        .bind(&total_count)
        .execute(pool)
        .await?;
    }

    Ok(())
}

/// Add a single MailHistoryInfo record from a Rust struct.
pub async fn add_mail_history_info(pool: &SqlitePool, data: &MailHistoryInfo) -> sqlx::Result<()> {
    sqlx::query(
        r#"
INSERT INTO MailHistoryInfo (
    Uid,
    MailInfoIndex,
    TotalCount
) VALUES (
    ?,
    ?,
    ?
)
"#,
    )
    .bind(&data.uid)
    .bind(&data.mail_info_index)
    .bind(&data.total_count)
    .execute(pool)
    .await?;

    Ok(())
}

/// Fetch all records for a given UID.
pub async fn get_mail_history_info(
    pool: &SqlitePool,
    uid: i64,
) -> sqlx::Result<Vec<MailHistoryInfo>> {
    sqlx::query_as::<_, MailHistoryInfo>("SELECT * FROM MailHistoryInfo WHERE Uid = ?")
        .bind(uid)
        .fetch_all(pool)
        .await
}

/// Delete all MailHistoryInfo rows for a UID.
pub async fn delete_mail_history_info(pool: &SqlitePool, uid: i64) -> sqlx::Result<()> {
    sqlx::query("DELETE FROM MailHistoryInfo WHERE Uid = ?")
        .bind(uid)
        .execute(pool)
        .await?;
    Ok(())
}
