// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System.Collections.Generic;
using System.Text;

namespace autoShell.Generators;

/// <summary>
/// Emits C# source code for action parameter record classes.
/// </summary>
internal static class RecordEmitter
{
    /// <summary>
    /// Generates a single C# source file containing all action parameter records.
    /// </summary>
    public static string Emit(List<ActionDefinition> actions, string schemaFileName)
    {
        var sb = new StringBuilder();

        sb.AppendLine("// <auto-generated/>");
        sb.AppendLine($"// Generated from {schemaFileName}");
        sb.AppendLine();
        sb.AppendLine("using System.Text.Json.Serialization;");
        sb.AppendLine();
        sb.AppendLine("namespace autoShell.Handlers.Generated;");
        sb.AppendLine();

        foreach (var action in actions)
        {
            EmitRecord(sb, action);
            sb.AppendLine();
        }

        return sb.ToString();
    }

    private static void EmitRecord(StringBuilder sb, ActionDefinition action)
    {
        sb.AppendLine($"/// <summary>");
        sb.AppendLine($"/// Parameters for the {action.ActionName} action.");
        sb.AppendLine($"/// </summary>");

        if (action.Parameters.Count == 0)
        {
            sb.AppendLine($"internal record {action.TypeName};");
            return;
        }

        sb.AppendLine($"internal record {action.TypeName}");
        sb.AppendLine("{");

        foreach (var param in action.Parameters)
        {
            sb.AppendLine($"    [JsonPropertyName(\"{param.JsonName}\")]");
            sb.AppendLine($"    public {param.CSharpType} {param.CSharpName} {{ get; init; }} = {param.DefaultValue};");
            sb.AppendLine();
        }

        sb.AppendLine("}");
    }
}
