using General_Ledger_Service.DTOs.AuditLog; using General_Ledger_Service.DTOs.Common; using General_Ledger_Service.Enums; using General_Ledger_Service.Interfaces.Repositories; using General_Ledger_Service.Interfaces.Services; namespace General_Ledger_Service.Services { public class AuditLogService(IAuditLogRepository auditLogRepository) : IAuditLogService { private readonly IAuditLogRepository _auditLogRepository = auditLogRepository; public async Task ListAsync(ListAuditLogRequest request) { // No default page/pageSize - paging is only applied when the caller explicitly // supplies both (RepositoryHelpers.ApplyPaging); a non-positive value is treated as // "not supplied" rather than silently substituted with one. var page = request.Page is > 0 ? request.Page : null; var pageSize = request.PageSize is > 0 ? request.PageSize : null; var paged = page.HasValue && pageSize.HasValue; List categories; if (request.Category is null || request.Category.Count == 0) { categories = [AuditCategory.Ledger, AuditCategory.Administrative]; } else { categories = [.. request.Category .Select(c => Enum.TryParse(c, ignoreCase: true, out var parsed) ? (AuditCategory?)parsed : null) .Where(c => c.HasValue) .Select(c => c!.Value) .Distinct()]; // A typo'd category matches nothing, rather than falling back to "match everything". if (categories.Count == 0) { return EmptyResponse(paged ? page : null, paged ? pageSize : null); } } AuditAction? action = null; if (!string.IsNullOrWhiteSpace(request.Action)) { if (!Enum.TryParse(request.Action, ignoreCase: true, out var parsedAction)) { return EmptyResponse(paged ? page : null, paged ? pageSize : null); } action = parsedAction; } var (items, totalCount) = await _auditLogRepository.ListAsync( categories, request.EntityName, action, request.PerformedBy, request.From, request.To, page, pageSize); return ResponseHelpers.Ok("Audit log retrieved successfully", new AuditLogListResponse { Items = items, TotalCount = totalCount, Page = paged ? page : null, PageSize = paged ? pageSize : null }); } private static ApiResponse EmptyResponse(int? page, int? pageSize) => ResponseHelpers.Ok("Audit log retrieved successfully", new AuditLogListResponse { Items = [], TotalCount = 0, Page = page, PageSize = pageSize }); } }