//! File-first configuration for the minimal credit-control reference service.

use photon_config::load_toml_config;
use photon_state::StateBackend;
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use std::path::Path;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
    #[serde(default = "default_listen_addr")]
    pub listen_addr: SocketAddr,
    #[serde(default = "default_http_addr")]
    pub http_addr: SocketAddr,
    #[serde(default)]
    pub flaredb_endpoint: Option<String>,
    #[serde(default)]
    pub storage_backend: StateBackend,
    #[serde(default)]
    pub database_url: Option<String>,
    #[serde(default)]
    pub single_node: bool,
    #[serde(default)]
    pub chainfire_endpoint: Option<String>,
    #[serde(default = "default_iam_server_addr")]
    pub iam_server_addr: String,
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            listen_addr: default_listen_addr(),
            http_addr: default_http_addr(),
            flaredb_endpoint: None,
            storage_backend: StateBackend::Flaredb,
            database_url: None,
            single_node: false,
            chainfire_endpoint: None,
            iam_server_addr: default_iam_server_addr(),
        }
    }
}

pub fn load_config(path: &Path) -> anyhow::Result<ServerConfig> {
    load_toml_config(path)
}

fn default_listen_addr() -> SocketAddr {
    "0.0.0.0:50057".parse().unwrap()
}

fn default_http_addr() -> SocketAddr {
    "127.0.0.1:8086".parse().unwrap()
}

fn default_iam_server_addr() -> String {
    "127.0.0.1:50080".to_string()
}
