use axum::{ extract::{Path, State}, Json, }; use serde_json::{json, Value}; use crate::{ app::AppState, error::AppResult, models::squad::SaveSquadRequest, services::{club as club_svc, profile as profile_svc, squad as squad_svc}, }; pub async fn get_squad(State(state): State) -> AppResult> { let profile = profile_svc::get_active_profile(&state.pool).await?; let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?; let (squad, players) = squad_svc::get_squad(&state.pool, &club.id).await?; let chemistry = squad_svc::calculate_chemistry(&state.pool, &state.card_db, &players).await?; Ok(Json(squad_response(&squad, &players, chemistry))) } pub async fn get_squads(State(state): State) -> AppResult> { let profile = profile_svc::get_active_profile(&state.pool).await?; let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?; let squads = squad_svc::list_squads(&state.pool, &club.id).await?; Ok(Json(json!({ "squads": squads }))) } pub async fn get_squad_by_id( State(state): State, Path(squad_id): Path, ) -> AppResult> { let profile = profile_svc::get_active_profile(&state.pool).await?; let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?; let (squad, players) = squad_svc::get_squad_by_id(&state.pool, &club.id, &squad_id).await?; let chemistry = squad_svc::calculate_chemistry(&state.pool, &state.card_db, &players).await?; Ok(Json(squad_response(&squad, &players, chemistry))) } pub async fn post_squad( State(state): State, Json(req): Json, ) -> AppResult> { let profile = profile_svc::get_active_profile(&state.pool).await?; let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?; if !req.players.is_empty() { squad_svc::validate_formation(&state.pool, &state.card_db, &req.players).await?; } let squad = squad_svc::save_squad(&state.pool, &club.id, &req).await?; Ok(Json(json!({ "squad": squad }))) } pub async fn delete_squad( State(state): State, Path(squad_id): Path, ) -> AppResult> { let profile = profile_svc::get_active_profile(&state.pool).await?; let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?; squad_svc::delete_squad(&state.pool, &club.id, &squad_id).await?; Ok(Json(json!({ "deleted": squad_id }))) } fn squad_response( squad: &crate::models::squad::Squad, players: &[crate::models::squad::SquadPlayer], chemistry: Value, ) -> Value { let enriched: Vec = players .iter() .map(|sp| { json!({ "squad_player_id": sp.id, "owned_card_id": sp.owned_card_id, "position_index": sp.position_index, "is_captain": sp.is_captain, "is_on_bench": sp.is_on_bench, }) }) .collect(); json!({ "squad": { "id": squad.id, "name": squad.name, "formation": squad.formation, }, "players": enriched, "chemistry": chemistry, }) }