use axum::{extract::State, http::HeaderMap, response::Json};
use std::sync::Arc;

use crate::calendar::CalDAVClient;
use crate::{
    models::{
        ApiError, CreateCalendarRequest, CreateCalendarResponse, DeleteCalendarRequest,
        DeleteCalendarResponse,
    },
    AppState,
};

use super::auth::{extract_bearer_token, extract_password_header};

pub async fn create_calendar(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Json(request): Json<CreateCalendarRequest>,
) -> Result<Json<CreateCalendarResponse>, ApiError> {
    let token = extract_bearer_token(&headers)?;
    let password = extract_password_header(&headers)?;

    // Validate request
    if request.name.trim().is_empty() {
        return Err(ApiError::BadRequest(
            "Calendar name is required".to_string(),
        ));
    }

    // Create CalDAV config from token and password
    let config = state
        .auth_service
        .caldav_config_from_token(&token, &password)?;
    let client = CalDAVClient::new(config);

    // Create calendar on CalDAV server
    match client
        .create_calendar(
            &request.name,
            request.description.as_deref(),
            request.color.as_deref(),
        )
        .await
    {
        Ok(_) => Ok(Json(CreateCalendarResponse {
            success: true,
            message: "Calendar created successfully".to_string(),
        })),
        Err(e) => {
            eprintln!("Failed to create calendar: {}", e);
            Err(ApiError::Internal(format!(
                "Failed to create calendar: {}",
                e
            )))
        }
    }
}

pub async fn delete_calendar(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Json(request): Json<DeleteCalendarRequest>,
) -> Result<Json<DeleteCalendarResponse>, ApiError> {
    let token = extract_bearer_token(&headers)?;
    let password = extract_password_header(&headers)?;

    // Validate request
    if request.path.trim().is_empty() {
        return Err(ApiError::BadRequest(
            "Calendar path is required".to_string(),
        ));
    }

    // Create CalDAV config from token and password
    let config = state
        .auth_service
        .caldav_config_from_token(&token, &password)?;
    let client = CalDAVClient::new(config);

    // Delete calendar on CalDAV server
    match client.delete_calendar(&request.path).await {
        Ok(_) => Ok(Json(DeleteCalendarResponse {
            success: true,
            message: "Calendar deleted successfully".to_string(),
        })),
        Err(e) => {
            eprintln!("Failed to delete calendar: {}", e);
            Err(ApiError::Internal(format!(
                "Failed to delete calendar: {}",
                e
            )))
        }
    }
}
