//! Kirjastomoduuli — julkinen API integraatiotesteille.

pub mod handlers;
pub mod models;

use axum::routing::{delete, get, post, put};
use axum::Router;
use sqlx::SqlitePool;
use tower_http::cors::CorsLayer;

/// Luo reititin annetulla tietokantapoolilla.
pub fn app(pool: SqlitePool) -> Router {
    Router::new()
        .route("/todos", post(handlers::create_todo))
        .route("/todos", get(handlers::list_todos))
        .route("/todos/{id}", get(handlers::get_todo))
        .route("/todos/{id}", put(handlers::update_todo))
        .route("/todos/{id}", delete(handlers::delete_todo))
        .layer(CorsLayer::permissive())
        .with_state(pool)
}

/// Alusta tietokantataulu.
pub async fn init_db(pool: &SqlitePool) {
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS todos (
            id          INTEGER PRIMARY KEY AUTOINCREMENT,
            title       TEXT NOT NULL,
            description TEXT,
            due_date    TEXT,
            priority    INTEGER NOT NULL DEFAULT 1,
            status      TEXT NOT NULL DEFAULT 'pending'
        )",
    )
    .execute(pool)
    .await
    .expect("Taulun luonti epäonnistui");
}
