use axum::{ extract::{Path, State}, response::Json, http::StatusCode, Router, routing::get, }; use crate::auth::structs::AppState; use crate::state::structs::{County, ErrorResponse}; pub fn router() -> Router { Router::new() .route("/state/:state_abbr", get(get_counties_by_state)) .route("/state/:state_abbr/:county_id", get(get_county_by_id)) } pub async fn get_counties_by_state( State(app_state): State, Path(state_abbr): Path, ) -> Result>, (StatusCode, Json)> { let state_abbr_upper = state_abbr.to_uppercase(); println!("Querying counties for state: {}", state_abbr_upper); match sqlx::query_as::<_, County>("SELECT id, name, state FROM county WHERE UPPER(state) = $1 ORDER BY name ASC") .bind(&state_abbr_upper) .fetch_all(&*app_state.db) .await { Ok(counties) => { if counties.is_empty() { Err(( StatusCode::NOT_FOUND, Json(ErrorResponse { error: format!("No counties found for state abbreviation: {}", state_abbr_upper), }), )) } else { Ok(Json(counties)) } } Err(e) => { eprintln!("Database error fetching counties for state {}: {}", state_abbr_upper, e); Err(( StatusCode::INTERNAL_SERVER_ERROR, Json(ErrorResponse { error: "Failed to retrieve counties. Please try again later.".to_string(), }), )) } } } pub async fn get_county_by_id( State(app_state): State, Path((state_abbr, county_id)): Path<(String, i32)>, ) -> Result, (StatusCode, Json)> { let state_abbr_upper = state_abbr.to_uppercase(); println!("Querying county with ID: {} for state: {}", county_id, state_abbr_upper); match sqlx::query_as::<_, County>("SELECT id, name, state FROM county WHERE UPPER(state) = $1 AND id = $2") .bind(&state_abbr_upper) .bind(county_id) .fetch_one(&*app_state.db) .await { Ok(county) => Ok(Json(county)), Err(sqlx::Error::RowNotFound) => Err(( StatusCode::NOT_FOUND, Json(ErrorResponse { error: format!("County with ID {} not found in state {}", county_id, state_abbr_upper), }), )), Err(e) => { eprintln!("Database error fetching county with ID {} for state {}: {}", county_id, state_abbr_upper, e); Err(( StatusCode::INTERNAL_SERVER_ERROR, Json(ErrorResponse { error: "Failed to retrieve county. Please try again later.".to_string(), }), )) } } }