using System.Security;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NTP.Application.Refinery.Integrations;
namespace NTP.Infrastructure.Integrations;
///
/// Section Refinery:Jopetrol. OFF by default. and are secrets: they come only from the
/// environment / server .env (Refinery__Jopetrol__UserName, Refinery__Jopetrol__Password), never from a file in the repository.
///
public sealed class JopetrolOptions
{
public const string SectionName = "Refinery:Jopetrol";
public const string HttpClientName = "Jopetrol";
public bool Enabled { get; set; }
/// The ASMX endpoint of the Jopetrol TransportPaymentWS service.
public string Url { get; set; } = "";
public string UserName { get; set; } = "";
public string Password { get; set; } = "";
public int TimeoutSeconds { get; set; } = 30;
}
/// Request building and answer parsing of the Jopetrol SOAP call (kept apart from the HTTP code so it can be tested).
public static class JopetrolSoap
{
public const string SoapNamespace = "http://www.w3.org/2003/05/soap-envelope";
public const string ServiceNamespace = "http://jopetrol.com.jo/TransportPaymentWS";
/// The envelope of legacy callRefinaryUpdateStatusTo7 (SOAP 1.2, AuthHeader + sendClaimandUpdateStatusTo7 with TransNumber and claimNo).
public static string BuildEnvelope(string userName, string password, string pn, string claimNo)
{
static string E(string s) => SecurityElement.Escape(s) ?? "";
return $"""
{E(userName)}{E(password)}
{E(pn)}{E(claimNo)}
""";
}
/// Text of sendClaimandUpdateStatusTo7Result (legacy xmlSearch "//*[local-name()=...]"); null when the answer does not contain it.
public static string? ParseResult(string xml)
{
var doc = XDocument.Parse(xml);
return doc.Descendants().FirstOrDefault(e => e.Name.LocalName == "sendClaimandUpdateStatusTo7Result")?.Value;
}
}
///
/// Jopetrol claim web service (legacy refinery_wage_claimfactory.callRefinaryUpdateStatusTo7). Returns null WITHOUT any call when
/// Refinery:Jopetrol:Enabled is false. HTTP errors, time-outs and unreadable answers are thrown (the caller decides what to tell the user).
///
public sealed class JopetrolGateway(IHttpClientFactory httpClients, IOptions options, ILogger logger) : IJopetrolGateway
{
public async Task SendClaimAndUpdateStatusTo7Async(string pn, string claimNo, CancellationToken ct = default)
{
var o = options.Value;
if (!o.Enabled) return null;
if (string.IsNullOrWhiteSpace(o.Url) || string.IsNullOrWhiteSpace(o.UserName) || string.IsNullOrWhiteSpace(o.Password))
throw new InvalidOperationException("Refinery:Jopetrol is enabled but Url / UserName / Password are not configured.");
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(o.TimeoutSeconds is > 0 and <= 300 ? o.TimeoutSeconds : 30));
using var request = new HttpRequestMessage(HttpMethod.Post, o.Url)
{
Content = new StringContent(JopetrolSoap.BuildEnvelope(o.UserName, o.Password, pn, claimNo), Encoding.UTF8, "text/xml"),
};
using var response = await httpClients.CreateClient(JopetrolOptions.HttpClientName).SendAsync(request, cts.Token);
var body = await response.Content.ReadAsStringAsync(cts.Token);
logger.LogInformation("Jopetrol sendClaimandUpdateStatusTo7 for permit {Pn}: HTTP {Status}", pn, (int)response.StatusCode);
// legacy parsed whatever came back; a SOAP fault or an HTML error page has no result element
try { return JopetrolSoap.ParseResult(body) ?? ""; }
catch (XmlException) { throw new InvalidOperationException($"Jopetrol answered HTTP {(int)response.StatusCode} with an unreadable body."); }
}
}