use crate::error::Result;
use crate::models::{BulletinV2, ApiResponse, PaginatedResponse};
use crate::utils::{
    response::success_response,
    pagination::PaginationHelper,
    urls::UrlBuilder,
};
use crate::services::BulletinService;
use axum::{
    extract::{Path, Query, State},
    Json,
};
use serde::Deserialize;
use uuid::Uuid;
use crate::AppState;

#[derive(Deserialize)]
pub struct BulletinQuery {
    page: Option<i32>,
    per_page: Option<i32>,
    // Note: timezone support removed - V2 uses UTC timestamps, client handles timezone conversion
}

pub async fn list(
    State(state): State<AppState>,
    Query(query): Query<BulletinQuery>,
) -> Result<Json<ApiResponse<PaginatedResponse<BulletinV2>>>> {
    let pagination = PaginationHelper::from_query(query.page, query.per_page);
    let url_builder = UrlBuilder::new();
    
    let (bulletins, total) = BulletinService::list_v2(
        &state.pool, 
        pagination.page, 
        pagination.per_page as i64, 
        false,
        &url_builder,
    ).await?;
    
    let response = pagination.create_response(bulletins, total);
    Ok(success_response(response))
}

pub async fn get_current(
    State(state): State<AppState>,
    Query(_query): Query<BulletinQuery>,
) -> Result<Json<ApiResponse<BulletinV2>>> {
    let url_builder = UrlBuilder::new();
    
    let bulletin = BulletinService::get_current_v2(&state.pool, &url_builder).await?
        .ok_or_else(|| crate::error::ApiError::NotFound("No current bulletin found".to_string()))?;
    
    Ok(success_response(bulletin))
}

pub async fn get_next(
    State(state): State<AppState>,
    Query(_query): Query<BulletinQuery>,
) -> Result<Json<ApiResponse<BulletinV2>>> {
    let url_builder = UrlBuilder::new();
    
    let bulletin = BulletinService::get_next_v2(&state.pool, &url_builder).await?
        .ok_or_else(|| crate::error::ApiError::NotFound("No next bulletin found".to_string()))?;
    
    Ok(success_response(bulletin))
}

pub async fn get_by_id(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    Query(_query): Query<BulletinQuery>,
) -> Result<Json<ApiResponse<BulletinV2>>> {
    let url_builder = UrlBuilder::new();
    
    let bulletin = BulletinService::get_by_id_v2(&state.pool, &id, &url_builder).await?
        .ok_or_else(|| crate::error::ApiError::NotFound("Bulletin not found".to_string()))?;
    
    Ok(success_response(bulletin))
}

