using System.Text.Json;
using eSPJ.Models;

namespace eSPJ.Services
{
    public class HistoryService
    {
        private readonly string _historyUpstFilePath;
        private readonly ILogger<HistoryService> _logger;

        public HistoryService(IWebHostEnvironment env, ILogger<HistoryService> logger)
        {
            _logger = logger;
            _historyUpstFilePath = Path.Combine(env.ContentRootPath, "Data", "history-upst.json");
        }

        public async Task<HistoryListResponse> GetUpstHistoryAsync(DateOnly? fromDate, DateOnly? toDate, int page = 1, int pageSize = 5)
        {
            page = page < 1 ? 1 : page;
            pageSize = pageSize <= 0 ? 5 : pageSize;

            var items = await ReadUpstHistoryAsync();
            var query = items.AsEnumerable();

            if (fromDate.HasValue)
            {
                query = query.Where(item => DateOnly.FromDateTime(item.TanggalWaktu) >= fromDate.Value);
            }

            if (toDate.HasValue)
            {
                query = query.Where(item => DateOnly.FromDateTime(item.TanggalWaktu) <= toDate.Value);
            }

            var ordered = query
                .OrderByDescending(item => item.TanggalWaktu)
                .ToList();

            var totalItems = ordered.Count;
            var totalPages = totalItems == 0 ? 1 : (int)Math.Ceiling(totalItems / (double)pageSize);
            var safePage = Math.Min(page, totalPages);
            var pagedItems = ordered
                .Skip((safePage - 1) * pageSize)
                .Take(pageSize)
                .ToList();

            return new HistoryListResponse
            {
                Items = pagedItems,
                Page = safePage,
                PageSize = pageSize,
                TotalItems = totalItems,
                TotalPages = totalPages,
                FromDate = fromDate?.ToString("yyyy-MM-dd"),
                ToDate = toDate?.ToString("yyyy-MM-dd")
            };
        }

        private async Task<List<HistoryItem>> ReadUpstHistoryAsync()
        {
            try
            {
                if (!File.Exists(_historyUpstFilePath))
                {
                    return new List<HistoryItem>();
                }

                var json = await File.ReadAllTextAsync(_historyUpstFilePath);
                var items = JsonSerializer.Deserialize<List<HistoryItem>>(json, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });

                return items ?? new List<HistoryItem>();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error reading UPST history JSON");
                return new List<HistoryItem>();
            }
        }
    }
}
