use axum::{extract::{Path, Query, State}, response::Json};
use crate::error::Result;
use crate::models::{ApiResponse, ScheduleData, ConferenceData, DateQuery};
use crate::services::{ScheduleService, CreateScheduleRequest};
use crate::utils::response::success_response;
use crate::AppState;

pub async fn get_schedule(
    State(state): State<AppState>,
    Query(params): Query<DateQuery>,
) -> Result<Json<ApiResponse<ScheduleData>>> {
    let date_str = params.date.unwrap_or_else(|| "2025-06-14".to_string());
    let schedule_data = ScheduleService::get_schedule_data_v1(&state.pool, &date_str).await?;
    
    Ok(success_response(schedule_data))
}

pub async fn get_conference_data(
    State(state): State<AppState>,
    Query(params): Query<DateQuery>,
) -> Result<Json<ApiResponse<ConferenceData>>> {
    let date_str = params.date.unwrap_or_else(|| "2025-06-14".to_string());
    let conference_data = ScheduleService::get_conference_data_v1(&state.pool, &date_str).await?;
    
    Ok(success_response(conference_data))
}

// Admin endpoints

pub async fn create_schedule(
    State(state): State<AppState>,
    Json(payload): Json<CreateScheduleRequest>,
) -> Result<Json<ApiResponse<crate::models::Schedule>>> {
    let created = ScheduleService::create_or_update_schedule(&state.pool, payload).await?;
    
    Ok(Json(ApiResponse {
        success: true,
        data: Some(created),
        message: Some("Schedule created successfully".to_string()),
    }))
}

pub async fn update_schedule(
    State(state): State<AppState>,
    Path(date_str): Path<String>,
    Json(mut payload): Json<CreateScheduleRequest>,
) -> Result<Json<ApiResponse<crate::models::Schedule>>> {
    // Override the date in the payload with the path parameter
    payload.date = date_str;
    
    let updated = ScheduleService::create_or_update_schedule(&state.pool, payload).await?;
    
    Ok(Json(ApiResponse {
        success: true,
        data: Some(updated),
        message: Some("Schedule updated successfully".to_string()),
    }))
}

pub async fn delete_schedule(
    State(state): State<AppState>,
    Path(date_str): Path<String>,
) -> Result<Json<ApiResponse<()>>> {
    ScheduleService::delete_schedule(&state.pool, &date_str).await?;
    
    Ok(Json(ApiResponse {
        success: true,
        data: None,
        message: Some("Schedule deleted successfully".to_string()),
    }))
}

pub async fn list_schedules(
    State(state): State<AppState>,
) -> Result<Json<ApiResponse<Vec<crate::models::Schedule>>>> {
    let schedules = ScheduleService::list_schedules_v1(&state.pool).await?;
    
    Ok(success_response(schedules))
}
