use std::env;

use aok::{OK, Void};
use log::info;
use systemd_reload::{Exit, Run, is_worker};

#[static_init::constructor(0)]
extern "C" fn _log_init() {
  log_init::init();
}

#[test]
fn test_is_worker() -> Void {
  // 测试 Worker 模式检测 / Test worker mode detection

  // 先清理环境变量确保干净状态 / Clean env var first to ensure clean state
  unsafe {
    env::remove_var("SYSTEMD_RELOAD_WORKER");
  }

  // 现在应该不是 worker / Now should not be worker
  if is_worker() {
    info!("⚠️ 环境变量已存在，跳过测试");
    return OK;
  }

  // 设置环境变量后应该是 worker / Should be worker after setting env var
  unsafe {
    env::set_var("SYSTEMD_RELOAD_WORKER", "true");
  }
  assert!(is_worker());

  // 清理环境变量 / Clean up env var
  unsafe {
    env::remove_var("SYSTEMD_RELOAD_WORKER");
  }
  assert!(!is_worker());

  info!("✓ is_worker 测试通过");
  OK
}

#[test]
fn test_run_creation() -> Void {
  // 测试 Run 结构体创建 / Test Run struct creation

  let _run1 = Run::new();
  let _run2 = Run::default();

  info!("✓ Run 创建测试通过");
  OK
}

#[test]
fn test_exit_struct() -> Void {
  // 测试 Exit 结构体 / Test Exit struct

  let exit1 = Exit {
    pid: 12345,
    code: Some(0),
  };

  let exit2 = Exit {
    pid: 67890,
    code: None,
  };

  assert_eq!(exit1.pid, 12345);
  assert_eq!(exit1.code, Some(0));
  assert_eq!(exit2.pid, 67890);
  assert_eq!(exit2.code, None);

  info!("✓ Exit 结构体测试通过");
  OK
}

#[tokio::test]
async fn test_run_basic() -> Void {
  // 测试 Run 基本功能 / Test Run basic functionality

  // 确保不在 worker 模式 / Ensure not in worker mode
  unsafe {
    env::remove_var("SYSTEMD_RELOAD_WORKER");
  }

  // 如果仍然是worker模式，跳过测试 / Skip test if still in worker mode
  if is_worker() {
    info!("⚠️ 仍在worker模式，跳过Run测试");
    return OK;
  }

  // 只测试创建，不运行主循环 / Only test creation, don't run main loop
  let _run = Run::new();

  info!("✓ Run 基本功能测试通过");
  OK
}

#[tokio::test]
async fn test_worker_mode_in_async() -> Void {
  // 异步环境中测试基本功能 / Test basic functionality in async context

  // 测试基本的结构体创建 / Test basic struct creation
  let _run = Run::new();
  let _exit = Exit {
    pid: 123,
    code: Some(0),
  };

  info!("✓ 异步环境基本功能测试通过");
  OK
}

#[test]
fn test_multiple_run_instances() -> Void {
  // 测试多个 Run 实例创建 / Test multiple Run instance creation

  let runs: Vec<Run> = (0..5).map(|_| Run::new()).collect();

  assert_eq!(runs.len(), 5);

  info!("✓ 多个 Run 实例测试通过");
  OK
}
