// <auto-generated/>

#nullable disable

using System;
using System.ClientModel;
using System.ClientModel.Primitives;
using System.Collections.Generic;
using System.Text.Json;
using OpenAI;

namespace OpenAI.Batch
{
    internal partial class InternalBatchJob : IJsonModel<InternalBatchJob>
    {
        internal InternalBatchJob() : this(null, null, null, null, null, null, default, null, null, default, default, default, default, default, default, default, default, default, null, null, null)
        {
        }

        void IJsonModel<InternalBatchJob>.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options)
        {
            writer.WriteStartObject();
            JsonModelWriteCore(writer, options);
            writer.WriteEndObject();
        }

        protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options)
        {
            string format = options.Format == "W" ? ((IPersistableModel<InternalBatchJob>)this).GetFormatFromOptions(options) : options.Format;
            if (format != "J")
            {
                throw new FormatException($"The model {nameof(InternalBatchJob)} does not support writing '{format}' format.");
            }
            if (_additionalBinaryDataProperties?.ContainsKey("id") != true)
            {
                writer.WritePropertyName("id"u8);
                writer.WriteStringValue(Id);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("object") != true)
            {
                writer.WritePropertyName("object"u8);
                writer.WriteStringValue(Object);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("endpoint") != true)
            {
                writer.WritePropertyName("endpoint"u8);
                writer.WriteStringValue(Endpoint);
            }
            if (Optional.IsDefined(Errors) && _additionalBinaryDataProperties?.ContainsKey("errors") != true)
            {
                writer.WritePropertyName("errors"u8);
                writer.WriteObjectValue(Errors, options);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("input_file_id") != true)
            {
                writer.WritePropertyName("input_file_id"u8);
                writer.WriteStringValue(InputFileId);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("completion_window") != true)
            {
                writer.WritePropertyName("completion_window"u8);
                writer.WriteStringValue(CompletionWindow);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("status") != true)
            {
                writer.WritePropertyName("status"u8);
                writer.WriteStringValue(Status.ToString());
            }
            if (Optional.IsDefined(OutputFileId) && _additionalBinaryDataProperties?.ContainsKey("output_file_id") != true)
            {
                writer.WritePropertyName("output_file_id"u8);
                writer.WriteStringValue(OutputFileId);
            }
            if (Optional.IsDefined(ErrorFileId) && _additionalBinaryDataProperties?.ContainsKey("error_file_id") != true)
            {
                writer.WritePropertyName("error_file_id"u8);
                writer.WriteStringValue(ErrorFileId);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("created_at") != true)
            {
                writer.WritePropertyName("created_at"u8);
                writer.WriteNumberValue(CreatedAt, "U");
            }
            if (Optional.IsDefined(InProgressAt) && _additionalBinaryDataProperties?.ContainsKey("in_progress_at") != true)
            {
                writer.WritePropertyName("in_progress_at"u8);
                writer.WriteNumberValue(InProgressAt.Value, "U");
            }
            if (Optional.IsDefined(ExpiresAt) && _additionalBinaryDataProperties?.ContainsKey("expires_at") != true)
            {
                writer.WritePropertyName("expires_at"u8);
                writer.WriteNumberValue(ExpiresAt.Value, "U");
            }
            if (Optional.IsDefined(FinalizingAt) && _additionalBinaryDataProperties?.ContainsKey("finalizing_at") != true)
            {
                writer.WritePropertyName("finalizing_at"u8);
                writer.WriteNumberValue(FinalizingAt.Value, "U");
            }
            if (Optional.IsDefined(CompletedAt) && _additionalBinaryDataProperties?.ContainsKey("completed_at") != true)
            {
                writer.WritePropertyName("completed_at"u8);
                writer.WriteNumberValue(CompletedAt.Value, "U");
            }
            if (Optional.IsDefined(FailedAt) && _additionalBinaryDataProperties?.ContainsKey("failed_at") != true)
            {
                writer.WritePropertyName("failed_at"u8);
                writer.WriteNumberValue(FailedAt.Value, "U");
            }
            if (Optional.IsDefined(ExpiredAt) && _additionalBinaryDataProperties?.ContainsKey("expired_at") != true)
            {
                writer.WritePropertyName("expired_at"u8);
                writer.WriteNumberValue(ExpiredAt.Value, "U");
            }
            if (Optional.IsDefined(CancellingAt) && _additionalBinaryDataProperties?.ContainsKey("cancelling_at") != true)
            {
                writer.WritePropertyName("cancelling_at"u8);
                writer.WriteNumberValue(CancellingAt.Value, "U");
            }
            if (Optional.IsDefined(CancelledAt) && _additionalBinaryDataProperties?.ContainsKey("cancelled_at") != true)
            {
                writer.WritePropertyName("cancelled_at"u8);
                writer.WriteNumberValue(CancelledAt.Value, "U");
            }
            if (Optional.IsDefined(RequestCounts) && _additionalBinaryDataProperties?.ContainsKey("request_counts") != true)
            {
                writer.WritePropertyName("request_counts"u8);
                writer.WriteObjectValue(RequestCounts, options);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("metadata") != true)
            {
                if (Optional.IsCollectionDefined(Metadata))
                {
                    writer.WritePropertyName("metadata"u8);
                    writer.WriteStartObject();
                    foreach (var item in Metadata)
                    {
                        writer.WritePropertyName(item.Key);
                        if (item.Value == null)
                        {
                            writer.WriteNullValue();
                            continue;
                        }
                        writer.WriteStringValue(item.Value);
                    }
                    writer.WriteEndObject();
                }
                else
                {
                    writer.WriteNull("metadata"u8);
                }
            }
            // Plugin customization: remove options.Format != "W" check
            if (_additionalBinaryDataProperties != null)
            {
                foreach (var item in _additionalBinaryDataProperties)
                {
                    if (ModelSerializationExtensions.IsSentinelValue(item.Value))
                    {
                        continue;
                    }
                    writer.WritePropertyName(item.Key);
#if NET6_0_OR_GREATER
                    writer.WriteRawValue(item.Value);
#else
                    using (JsonDocument document = JsonDocument.Parse(item.Value))
                    {
                        JsonSerializer.Serialize(writer, document.RootElement);
                    }
#endif
                }
            }
        }

        InternalBatchJob IJsonModel<InternalBatchJob>.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options);

        protected virtual InternalBatchJob JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options)
        {
            string format = options.Format == "W" ? ((IPersistableModel<InternalBatchJob>)this).GetFormatFromOptions(options) : options.Format;
            if (format != "J")
            {
                throw new FormatException($"The model {nameof(InternalBatchJob)} does not support reading '{format}' format.");
            }
            using JsonDocument document = JsonDocument.ParseValue(ref reader);
            return DeserializeInternalBatchJob(document.RootElement, options);
        }

        internal static InternalBatchJob DeserializeInternalBatchJob(JsonElement element, ModelReaderWriterOptions options)
        {
            if (element.ValueKind == JsonValueKind.Null)
            {
                return null;
            }
            string id = default;
            string @object = default;
            string endpoint = default;
            InternalBatchErrors errors = default;
            string inputFileId = default;
            string completionWindow = default;
            InternalBatchStatus status = default;
            string outputFileId = default;
            string errorFileId = default;
            DateTimeOffset createdAt = default;
            DateTimeOffset? inProgressAt = default;
            DateTimeOffset? expiresAt = default;
            DateTimeOffset? finalizingAt = default;
            DateTimeOffset? completedAt = default;
            DateTimeOffset? failedAt = default;
            DateTimeOffset? expiredAt = default;
            DateTimeOffset? cancellingAt = default;
            DateTimeOffset? cancelledAt = default;
            InternalBatchRequestCounts requestCounts = default;
            IDictionary<string, string> metadata = default;
            IDictionary<string, BinaryData> additionalBinaryDataProperties = new ChangeTrackingDictionary<string, BinaryData>();
            foreach (var prop in element.EnumerateObject())
            {
                if (prop.NameEquals("id"u8))
                {
                    id = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("object"u8))
                {
                    @object = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("endpoint"u8))
                {
                    endpoint = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("errors"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    errors = InternalBatchErrors.DeserializeInternalBatchErrors(prop.Value, options);
                    continue;
                }
                if (prop.NameEquals("input_file_id"u8))
                {
                    inputFileId = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("completion_window"u8))
                {
                    completionWindow = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("status"u8))
                {
                    status = new InternalBatchStatus(prop.Value.GetString());
                    continue;
                }
                if (prop.NameEquals("output_file_id"u8))
                {
                    outputFileId = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("error_file_id"u8))
                {
                    errorFileId = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("created_at"u8))
                {
                    createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64());
                    continue;
                }
                if (prop.NameEquals("in_progress_at"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    inProgressAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64());
                    continue;
                }
                if (prop.NameEquals("expires_at"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    expiresAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64());
                    continue;
                }
                if (prop.NameEquals("finalizing_at"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    finalizingAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64());
                    continue;
                }
                if (prop.NameEquals("completed_at"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    completedAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64());
                    continue;
                }
                if (prop.NameEquals("failed_at"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    failedAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64());
                    continue;
                }
                if (prop.NameEquals("expired_at"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    expiredAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64());
                    continue;
                }
                if (prop.NameEquals("cancelling_at"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    cancellingAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64());
                    continue;
                }
                if (prop.NameEquals("cancelled_at"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    cancelledAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64());
                    continue;
                }
                if (prop.NameEquals("request_counts"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    requestCounts = InternalBatchRequestCounts.DeserializeInternalBatchRequestCounts(prop.Value, options);
                    continue;
                }
                if (prop.NameEquals("metadata"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        metadata = new ChangeTrackingDictionary<string, string>();
                        continue;
                    }
                    Dictionary<string, string> dictionary = new Dictionary<string, string>();
                    foreach (var prop0 in prop.Value.EnumerateObject())
                    {
                        if (prop0.Value.ValueKind == JsonValueKind.Null)
                        {
                            dictionary.Add(prop0.Name, null);
                        }
                        else
                        {
                            dictionary.Add(prop0.Name, prop0.Value.GetString());
                        }
                    }
                    metadata = dictionary;
                    continue;
                }
                // Plugin customization: remove options.Format != "W" check
                additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText()));
            }
            return new InternalBatchJob(
                id,
                @object,
                endpoint,
                errors,
                inputFileId,
                completionWindow,
                status,
                outputFileId,
                errorFileId,
                createdAt,
                inProgressAt,
                expiresAt,
                finalizingAt,
                completedAt,
                failedAt,
                expiredAt,
                cancellingAt,
                cancelledAt,
                requestCounts,
                metadata,
                additionalBinaryDataProperties);
        }

        BinaryData IPersistableModel<InternalBatchJob>.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options);

        protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options)
        {
            string format = options.Format == "W" ? ((IPersistableModel<InternalBatchJob>)this).GetFormatFromOptions(options) : options.Format;
            switch (format)
            {
                case "J":
                    return ModelReaderWriter.Write(this, options, OpenAIContext.Default);
                default:
                    throw new FormatException($"The model {nameof(InternalBatchJob)} does not support writing '{options.Format}' format.");
            }
        }

        InternalBatchJob IPersistableModel<InternalBatchJob>.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options);

        protected virtual InternalBatchJob PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options)
        {
            string format = options.Format == "W" ? ((IPersistableModel<InternalBatchJob>)this).GetFormatFromOptions(options) : options.Format;
            switch (format)
            {
                case "J":
                    using (JsonDocument document = JsonDocument.Parse(data))
                    {
                        return DeserializeInternalBatchJob(document.RootElement, options);
                    }
                default:
                    throw new FormatException($"The model {nameof(InternalBatchJob)} does not support reading '{options.Format}' format.");
            }
        }

        string IPersistableModel<InternalBatchJob>.GetFormatFromOptions(ModelReaderWriterOptions options) => "J";

        public static explicit operator InternalBatchJob(ClientResult result)
        {
            using PipelineResponse response = result.GetRawResponse();
            using JsonDocument document = JsonDocument.Parse(response.Content);
            return DeserializeInternalBatchJob(document.RootElement, ModelSerializationExtensions.WireOptions);
        }
    }
}
