using System;
using System.Collections.Generic;
using StellaOps.Cryptography;

namespace StellaOps.Configuration;

public sealed class AuthoritySigningOptions
{
    /// <summary>
    /// Determines whether signing is enabled for revocation exports.
    /// </summary>
    public bool Enabled { get; set; } = true;

    /// <summary>
    /// Signing algorithm identifier (ES256 by default).
    /// </summary>
    public string Algorithm { get; set; } = SignatureAlgorithms.Es256;

    /// <summary>
    /// Identifier for the signing key source (e.g. "file", "vault").
    /// </summary>
    public string KeySource { get; set; } = "file";

    /// <summary>
    /// Active signing key identifier (kid).
    /// </summary>
    public string ActiveKeyId { get; set; } = string.Empty;

    /// <summary>
    /// Path to the private key material (PEM-encoded).
    /// </summary>
    public string KeyPath { get; set; } = string.Empty;

    /// <summary>
    /// Optional provider hint (default provider when null).
    /// </summary>
    public string? Provider { get; set; }

    /// <summary>
    /// Optional passphrase protecting the private key (not yet supported).
    /// </summary>
    public string? KeyPassphrase { get; set; }

    /// <summary>
    /// Additional signing keys retained for verification (previous rotations).
    /// </summary>
    public IList<AuthoritySigningAdditionalKeyOptions> AdditionalKeys { get; } = new List<AuthoritySigningAdditionalKeyOptions>();

    internal void Validate()
    {
        if (!Enabled)
        {
            return;
        }

        if (string.IsNullOrWhiteSpace(ActiveKeyId))
        {
            throw new InvalidOperationException("Authority signing configuration requires signing.activeKeyId.");
        }

        if (string.IsNullOrWhiteSpace(KeyPath))
        {
            throw new InvalidOperationException("Authority signing configuration requires signing.keyPath.");
        }

        if (string.IsNullOrWhiteSpace(Algorithm))
        {
            Algorithm = SignatureAlgorithms.Es256;
        }

        if (string.IsNullOrWhiteSpace(KeySource))
        {
            KeySource = "file";
        }

        foreach (var key in AdditionalKeys)
        {
            key.Validate(KeySource);
        }
    }
}
