namespace Csob.Configuration;

/// <summary>
/// Service configuration resolved from environment variables.
///
/// This service is a stateless, multi-tenant proxy in front of the ČSOB PSD2 (Open Banking)
/// API. Unlike the sibling iDoklad service, it holds <b>no per-client secrets</b>: the eIDAS
/// client certificate, OAuth client id/secret, access token, API key and TPP name are all
/// supplied per request as HTTP headers by the calling client service
/// (see <see cref="Credentials.CredentialConstants"/>). Only non-secret infrastructure
/// configuration (API/OAuth base URLs, app metadata, reverse-proxy prefix, timeout) lives here.
/// </summary>
public sealed class CsobSettings
{
    public string AppName { get; init; } = GetEnv("APP_NAME", "ČSOB PSD2 Service");
    public string AppVersion { get; init; } = GetEnv("APP_VERSION", "1.0.0");

    /// <summary>Public reverse-proxy prefix (e.g. <c>/apps/csob</c>) injected by AppFactory.</summary>
    public string RootPath { get; init; } = GetEnv("ROOT_PATH", string.Empty);

    /// <summary>
    /// Base URL of the ČSOB PSD2 resource API. Production default; override for any other
    /// environment. All AISP/PISP/consent path templates are appended to this base.
    /// </summary>
    public string ApiBaseUrl { get; init; } =
        GetEnv("CSOB_API_BASE_URL", "https://api.csob.cz/api/csob/psd2/v1");

    /// <summary>
    /// OAuth2 authorization endpoint (Authorization Code flow, PSU redirect). Production default;
    /// verify against the current ČSOB developer portal as the host may change.
    /// </summary>
    public string OAuthAuthorizeUrl { get; init; } =
        GetEnv("CSOB_OAUTH_AUTHORIZE_URL", "https://identita.csob.cz/mep/fs/fl/oauth2/auth");

    /// <summary>
    /// OAuth2 token endpoint (code-&gt;token and refresh). Production default; verify against the
    /// current ČSOB developer portal.
    /// </summary>
    public string OAuthTokenUrl { get; init; } =
        GetEnv("CSOB_OAUTH_TOKEN_URL", "https://api.csob.cz/api/csob/oauth2/v1/token");

    /// <summary>Upstream HTTP request timeout in seconds.</summary>
    public int RequestTimeoutSeconds { get; init; } =
        ParseInt(GetEnv("CSOB_REQUEST_TIMEOUT_SECONDS", "100"), 100);

    private static string GetEnv(string name, string fallback)
    {
        var value = Environment.GetEnvironmentVariable(name);
        return string.IsNullOrWhiteSpace(value) ? fallback : value;
    }

    private static int ParseInt(string value, int fallback) =>
        int.TryParse(value, out var parsed) && parsed > 0 ? parsed : fallback;
}
