// This file is auto-generated by alef — DO NOT EDIT.
// alef:hash:4e15143f4af1ae8bafbdb1506ef057da924484c66a19483966333558ad437e75
// To regenerate: alef generate
// To verify freshness: alef verify --exit-code
// Issues & docs: https://github.com/kreuzberg-dev/alef
#nullable enable

using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Kreuzberg;

/// <summary>
/// API server configuration.
///
/// This struct holds all configuration options for the Kreuzberg API server,
/// including host/port settings, CORS configuration, and upload limits.
///
/// # Defaults
///
/// - `host`: "127.0.0.1" (localhost only)
/// - `port`: 8000
/// - `cors_origins`: empty vector (allows all origins)
/// - `max_request_body_bytes`: 104_857_600 (100 MB)
/// - `max_multipart_field_bytes`: 104_857_600 (100 MB)
/// </summary>
public sealed record ServerConfig
{
    /// <summary>
    /// Server host address (e.g., "127.0.0.1", "0.0.0.0")
    /// </summary>
    [JsonPropertyName("host")]
    public string Host { get; init; } = "";

    /// <summary>
    /// Server port number
    /// </summary>
    [JsonPropertyName("port")]
    public ushort Port { get; init; } = 0;

    /// <summary>
    /// CORS allowed origins. Empty vector means allow all origins.
    ///
    /// If this is an empty vector, the server will accept requests from any origin.
    /// If populated with specific origins (e.g., `"https://example.com"`), only
    /// those origins will be allowed.
    /// </summary>
    [JsonPropertyName("cors_origins")]
    public List<string> CorsOrigins { get; init; } = [];

    /// <summary>
    /// Maximum size of request body in bytes (default: 100 MB)
    /// </summary>
    [JsonPropertyName("max_request_body_bytes")]
    public ulong MaxRequestBodyBytes { get; init; } = 0;

    /// <summary>
    /// Maximum size of multipart fields in bytes (default: 100 MB)
    /// </summary>
    [JsonPropertyName("max_multipart_field_bytes")]
    public ulong MaxMultipartFieldBytes { get; init; } = 0;


    /// <summary>
    /// Parse a <see cref="ServerConfig"/> from a JSON string.
    /// </summary>
    /// <exception cref="KreuzbergException">When the JSON cannot be deserialised.</exception>
    public static ServerConfig FromJson(string json)
    {
        try
        {
            return JsonSerializer.Deserialize<ServerConfig>(json, JsonOptions)
                ?? throw new KreuzbergException($"Failed to parse ServerConfig from JSON: deserializer returned null");
        }
        catch (KreuzbergException)
        {
            throw;
        }
        catch (Exception e)
        {
            throw new KreuzbergException($"Failed to parse ServerConfig from JSON: {e.Message}", e);
        }
    }

    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault,
        Converters = { new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseLower) },
    };

    /// <summary>Options for serializing config/input objects to FFI. Strips nulls
    /// (nullable C# fields default to null and would override required Rust fields with
    /// non-deserialisable nulls) but preserves explicit false/0 so caller intent is kept.</summary>
    private static readonly JsonSerializerOptions JsonSerializationOptions = new()
    {
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
        Converters = { new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseLower) },
    };

    public static ServerConfig Default()
    {
        var nativeResult = NativeMethods.ServerConfigDefault();
        var jsonPtr = NativeMethods.ServerConfigToJson(nativeResult);
        var json = global::System.Runtime.InteropServices.Marshal.PtrToStringUTF8(jsonPtr);
        NativeMethods.FreeString(jsonPtr);
        NativeMethods.ServerConfigFree(nativeResult);
        return JsonSerializer.Deserialize<ServerConfig>(json ?? "null", JsonOptions)!;
    }
}
