use actix_cors::Cors;
use actix_files::Files;
use actix_web::{App, HttpServer, web};
use backend_rust::api::{auth, health, invites, me, notifications, reminder_tasks, todos, users};
use backend_rust::app_data::AppData;
use std::env;
use std::path::PathBuf;
use tracing::{error, info};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let format = tracing_subscriber::fmt::format().pretty();
    tracing_subscriber::fmt().event_format(format).init();

    // 从环境变量读取配置，使用默认值
    let host = env::var("HOST").unwrap_or_else(|_| "0.0.0.0".to_string());
    let port: u16 = env::var("PORT")
        .unwrap_or_else(|_| "4000".to_string())
        .parse()
        .expect("PORT must be a valid number");

    // 上传目录配置
    let upload_dir = env::var("UPLOAD_DIR")
        .map(PathBuf::from)
        .unwrap_or_else(|_| PathBuf::from("./uploads"));

    let app_data = match AppData::new().await {
        Ok(app_data) => web::Data::new(app_data),
        Err(e) => {
            error!("Failed to connect to database: {}", e);
            std::process::exit(1);
        }
    };
    info!("Starting server on {}:{}", host, port);
    info!("Upload directory: {:?}", upload_dir);

    HttpServer::new(move || {
        let cors = Cors::default()
            .allow_any_header()
            .allow_any_method()
            .allow_any_origin();

        App::new()
            .wrap(cors)
            .app_data(app_data.clone())
            .configure(configure_routes)
            // 配置静态文件服务，用于提供上传的文件（如头像）
            .service(Files::new("/uploads", upload_dir.clone()).show_files_listing())
    })
    .bind((host, port))?
    .run()
    .await
}

fn configure_routes(m: &mut web::ServiceConfig) {
    m.service(health::routes())
        .service(auth::routes())
        .service(invites::routes())
        .service(me::routes())
        .service(notifications::routes())
        .service(todos::routes())
        .service(reminder_tasks::routes())
        .service(users::routes());
}
