use crate::{
    db,
    dtos::CompanyProfileDto,
    AppState, ServerError,
};
use axum::{
    extract::{Path, State},
    Json,
};
use service_kit::api;
use tracing::info;
use anyhow::Error as AnyhowError;

#[api(PUT, "/api/v1/companies")]
pub async fn upsert_company(
    State(state): State<AppState>,
    Json(payload): Json<CompanyProfileDto>,
) -> Result<(), ServerError> {
    info!(target: "api", symbol = %payload.symbol, "PUT /companies → upsert_company called");
    db::upsert_company(&state.pool, &payload).await.map_err(AnyhowError::from)?;
    info!(target: "api", symbol = %payload.symbol, "upsert_company completed");
    Ok(())
}

#[api(GET, "/api/v1/companies/{symbol}")]
pub async fn get_company_by_symbol(
    State(state): State<AppState>,
    Path(symbol): Path<String>,
) -> Result<Json<CompanyProfileDto>, ServerError> {
    info!(target: "api", symbol = %symbol, "GET /companies/{{symbol}} → get_company_by_symbol called");
    let company = db::get_company_by_symbol(&state.pool, &symbol)
        .await
        .map_err(AnyhowError::from)?
        .ok_or_else(|| ServerError::NotFound(format!("Company with symbol '{}' not found", symbol)))?;

    // Convert from model to DTO
    let dto = CompanyProfileDto {
        symbol: company.symbol,
        name: company.name,
        industry: company.industry,
        list_date: company.list_date,
        additional_info: company.additional_info,
    };

    info!(target: "api", symbol = %dto.symbol, "get_company_by_symbol completed");
    Ok(Json(dto))
}
