using CPRNIMS.Domain.Contracts.Reports; using CPRNIMS.Domain.UIContracts.Common; using CPRNIMS.Infrastructure.Dto.Inventory.Reports; using CPRNIMS.Infrastructure.Helper; using FastReport; using Microsoft.Extensions.Configuration; using System.Data; using System.Net.Http.Json; using System.Text.Json; namespace CPRNIMS.Infrastructure.Reports { public class ReportBuilder : IReportBuilder { private readonly IConfiguration _configuration; private readonly TokenHelper _tokenHelper; private readonly IApiConfigurationService _apiConfigurationService; public ReportBuilder(IConfiguration configuration, TokenHelper tokenHelper, IApiConfigurationService apiConfigurationService) { _configuration = configuration; _tokenHelper = tokenHelper; _apiConfigurationService = apiConfigurationService; } private static readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; public Task MRSBuildAsync(DateTime dateFrom, DateTime dateTo, string templatePath, CancellationToken ct) { throw new NotImplementedException(); } public async Task RISBuildAsync( DateTime dateFrom, DateTime dateTo, string templatePath, CancellationToken ct = default) { var token = await _tokenHelper.GetValidTokenAsync(); if (string.IsNullOrEmpty(token)) throw new InvalidOperationException("Token has been expired."); var endpoint = _configuration["LLI:NonInvent:InventoryMgmt:RISReportData"] ?? throw new InvalidOperationException("RISReportData endpoint is not configured."); // Append the date range as query string var url = $"{endpoint}?dateFrom={dateFrom:yyyy-MM-dd}&dateTo={dateTo:yyyy-MM-dd}"; using var httpClient = _apiConfigurationService.CreateHttpClientWithDefaultHeaders(token); var response = await httpClient.GetAsync(url, ct); var json = await response.Content.ReadAsStringAsync(ct); if (!response.IsSuccessStatusCode) throw new InvalidOperationException( $"Failed to fetch RIS report data. HTTP {(int)response.StatusCode}: {json}"); var dto = JsonSerializer.Deserialize(json, _jsonOptions) ?? new RISReportDataDto(); var report = new Report(); report.Load(templatePath); // RegisterData accepts IEnumerable — names must match the .frx datasources. report.RegisterData(dto.Rows ?? new(), "TRIS"); report.RegisterData(dto.Disciplines ?? new(), "TDisciplineAgg"); report.RegisterData(dto.Recipients ?? new(), "TTopRecipients"); /* report.GetDataSource("Table").Enabled = true; report.GetDataSource("Table1").Enabled = true; report.GetDataSource("Table3").Enabled = true;*/ report.GetDataSource("TRIS").Enabled = true; report.GetDataSource("TDisciplineAgg").Enabled = true; report.GetDataSource("TTopRecipients").Enabled = true; report.SetParameterValue("DateFrom", dateFrom); report.SetParameterValue("DateTo", dateTo); return report; } } }