// SPDX-FileCopyrightText: Politik im Blick developers
// SPDX-FileCopyrightText: Wolfgang Silbermayr <wolfgang@silbermayr.at>
//
// SPDX-License-Identifier: AGPL-3.0-or-later OR EUPL-1.2

use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use pib_service_inventory::ParseMeetingStateError;
use serde::{Deserialize, Serialize};
use snafu::{IntoError, Snafu};

#[derive(Debug, Snafu)]
pub enum Error {
    Inventory {
        source: pib_service_inventory::Error,
    },
    MeetingStateParse {
        source: ParseMeetingStateError,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ApiError {
    pub message: String,
}

impl IntoResponse for Error {
    fn into_response(self) -> Response {
        let mut response = Json(ApiError {
            message: format!("{self}"),
        })
        .into_response();
        *response.status_mut() = if self.is_not_found() {
            StatusCode::NOT_FOUND
        } else {
            StatusCode::INTERNAL_SERVER_ERROR
        };
        response
    }
}

impl Error {
    pub fn is_not_found(&self) -> bool {
        matches!(
            self,
            Error::Inventory {
                source: pib_service_inventory::Error::NotFound
            }
        )
    }
}

impl From<pib_service_inventory::Error> for Error {
    fn from(source: pib_service_inventory::Error) -> Self {
        InventorySnafu.into_error(source)
    }
}

impl From<ParseMeetingStateError> for Error {
    fn from(source: ParseMeetingStateError) -> Self {
        MeetingStateParseSnafu.into_error(source)
    }
}
