use bd2::prost::Message;
use bd2::proto::proto_net::{
    Notify, PassDbInfo, PassInfoRequest, PassInfoResponse, PassRewardDbInfo,
};
use common::packet_code::PacketCodeType;
use crypto::network::GameResponse;
use serde_json::Value;
use tracing::info;

pub async fn handle(_pool: &sqlx::SqlitePool, _uid: i64, _req: PassInfoRequest) -> GameResponse {
    info!("Handling PassInfoRequest");

    // Load and parse JSON file
    let data: Value = serde_json::from_str(include_str!("../../../../data/starter/pass_info.json"))
        .expect("Failed to parse pass_info.json");

    // --- Parse passInfo array ---
    let passes = data
        .get("passInfo")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();

    let mut pass_info = Vec::new();

    for p in passes {
        pass_info.push(PassDbInfo {
            id: p.get("id").and_then(|v| v.as_i64()).map(|v| v as i32),
            exp: p.get("exp").and_then(|v| v.as_i64()).map(|v| v as i32),
            active_premium_1: p.get("activePremium_1").and_then(|v| v.as_bool()),
            ..Default::default()
        });
    }

    let rewards = data
        .get("passRewardInfo")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();

    let mut pass_reward_info = Vec::new();

    for r in rewards {
        pass_reward_info.push(PassRewardDbInfo {
            pass_id: r.get("passId").and_then(|v| v.as_i64()).map(|v| v as i32),
            id: r.get("id").and_then(|v| v.as_i64()).map(|v| v as i32),
            basic: r.get("basic").and_then(|v| v.as_bool()),
            premium_1: r.get("premium_1").and_then(|v| v.as_bool()),
            ..Default::default()
        });
    }

    let response = PassInfoResponse {
        pass_info,
        pass_reward_info,
        ..Default::default()
    };

    let resp_bytes = response.encode_to_vec();

    let notify = Notify {
        achievement_update_info: vec![],
        mission_update_info: vec![],
        event_mission_update_info: vec![],
        active_login_event: vec![1, 2, 625, 626, 627],
        active_contents_info: vec![],
        ll_type: Some("".to_string()),
        is_purchasing_disabled: Some(false),
        maintenance_start_date: Some(1688646600000),
        notice_last_seq: Some(8818),
        ..Default::default()
    };

    let (route, code) = PacketCodeType::PassInfo.info();
    GameResponse::success(route, &resp_bytes, code).with_notify(&notify)
}
