

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


namespace OnlineSalesAutoCrop.CoreAPI.Models.Responses.Integrations;

public sealed class SapODataResponse<T>
{
    [JsonPropertyName("d")]
    public SapODataResult<T> D { get; set; } = default!;
}

public sealed class SapODataResult<T>
{
    [JsonPropertyName("results")]
    public List<T> Results { get; set; } = new();
}

public sealed class IntegrationCustLedgerHttpResponse
{
    [JsonPropertyName("company")]
    public string Company { get; set; } = string.Empty;

    [JsonPropertyName("customer_no")]
    public string CustomerNo { get; set; } = string.Empty;   // stays string — SAP customer numbers can carry leading zeros

    [JsonPropertyName("current_balance")]
    [JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
    public decimal CurrentBalance { get; set; }

    [JsonPropertyName("overdue_amount")]
    [JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
    public decimal OverdueAmount { get; set; }

    [JsonPropertyName("currency")]
    public string Currency { get; set; } = string.Empty;

    [JsonPropertyName("overdue_date")]
    [JsonConverter(typeof(SapODataDateConverter))]
    public DateTime OverdueDate { get; set; }
}

public sealed class IntegrationMaterialStockHttpResponse
{
    [JsonPropertyName("plant")]
    public string PlantCode { get; set; } = string.Empty;

    [JsonPropertyName("material")]
    public string MaterialCode { get; set; } = string.Empty;   // stays string — SAP customer numbers can carry leading zeros

    [JsonPropertyName("available_stock")]
    [JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
    public decimal AvailableStock { get; set; }

    [JsonPropertyName("uom")]
    public string UOM { get; set; } = string.Empty;

}


public sealed class SapODataDateConverter : JsonConverter<DateTime>
{
    // Matches "/Date(1783641600000)/" and the rarer offset form "/Date(1783641600000+0600)/"
    private static readonly Regex Pattern = new(@"/Date\((-?\d+)(?:[+-]\d{4})?\)/", RegexOptions.Compiled);

    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var raw = reader.GetString();
        if (string.IsNullOrEmpty(raw))
            return default;

        var match = Pattern.Match(raw);
        if (!match.Success)
            throw new JsonException($"Unexpected SAP OData date format: '{raw}'");

        var ms = long.Parse(match.Groups[1].Value);
        return DateTimeOffset.FromUnixTimeMilliseconds(ms).UtcDateTime;
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        var ms = new DateTimeOffset(value, TimeSpan.Zero).ToUnixTimeMilliseconds();
        writer.WriteStringValue($"/Date({ms})/");
    }
}