use tower_service::Service;
use worker::{Context, Env, HttpRequest, console_log, event};

pub(crate) mod d1bridge;
pub(crate) mod entity;
pub(crate) mod route;
pub(crate) mod utility;

// https://developers.cloudflare.com/workers/languages/rust
#[event(fetch)]
async fn fetch(
    req: HttpRequest,
    env: Env,
    _ctx: Context,
) -> Result<axum::http::Response<axum::body::Body>, worker::Error> {
    console_error_panic_hook::set_once();

    // https://developers.cloudflare.com/d1/worker-api/
    let d1 = env.d1("D1TEST")?;
    let db = crate::d1bridge::connect_d1(d1)
        .await
        .map_err(|e| worker::Error::from(e.to_string()))?;
    console_log!("Connected to database");

    Ok(route::router(db).call(req).await?)
}
