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

    for entry in arr {
        let target_owner_index = entry
            .get("targetOwnerIndex")
            .and_then(|v| v.as_i64())
            .unwrap_or_default();

        sqlx::query(
            r#"
INSERT INTO MyLikeInfo (
    Uid,
    TargetOwnerIndex
) VALUES (
    ?,
    ?
)
"#
        )
        .bind(uid)
        .bind(&target_owner_index)
        .execute(pool)
        .await?;
    }

    Ok(())
}

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

    Ok(())
}

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

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