// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using FloraMultiPlatformFrontend.Application.Services.Interfaces;
using FloraMultiPlatformFrontend.Data.Repositories.Interfaces;
using FloraMultiPlatformFrontend.Presentation.Models.Diagnosis;
using Microsoft.Extensions.Logging;

namespace FloraMultiPlatformFrontend.Data.Repositories;

/// <summary>
/// Repository implementation for managing release configuration data
/// </summary>
public class SynopticConfigRepository : ISynopticConfigRepository
{
    private readonly ILogger<SynopticConfigRepository> _logger;
    private readonly IConfigurationService _configurationService;

    private List<SynopticPageConfiguration>? _cachedSynopticPage;
    private DateTime? _lastSynopticPageLoad;
    private readonly TimeSpan _cacheExpiry = TimeSpan.FromMinutes(5);

    private readonly JsonSerializerOptions _jsonOptions = new()
    {
        PropertyNameCaseInsensitive = true,
        AllowTrailingCommas = true,
        ReadCommentHandling = JsonCommentHandling.Skip
    };

    public SynopticConfigRepository(ILogger<SynopticConfigRepository> logger, IConfigurationService configurationService)
    {
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        _configurationService = configurationService;
    }

    /// <summary>
    /// Loads all release data from the configuration files
    /// </summary>
    public async Task<List<SynopticPageConfiguration>> GetReleaseDataAsync()
    {
        try
        {
            // Check if cached data is still valid
            if (_cachedReleaseData != null && _lastReleaseDataLoad.HasValue &&
                DateTime.UtcNow - _lastReleaseDataLoad.Value < _cacheExpiry)
            {
                _logger.LogDebug("Returning cached release data");
                return _cachedReleaseData;
            }

            _logger.LogInformation("Loading release data from ConfigurationService");
            var tbmConfig = await _configurationService.GetTbmConfigurationAsync();
            var releaseData = tbmConfig?.SynopticPages ?? new List<SynopticPageConfiguration>();

            _cachedReleaseData = releaseData;
            _lastReleaseDataLoad = DateTime.UtcNow;

            _logger.LogInformation("Successfully loaded {Count} release data items", releaseData.Count);
            return releaseData;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to load release data from ConfigurationService");
            return new List<SynopticPageConfiguration>();
        }
    }

    /// <summary>
    /// Loads release data filtered by group ID
    /// </summary>
    public async Task<List<SynopticPageConfiguration>> GetReleaseDataByGroupIdAsync(int groupId)
    {
        try
        {
            var allData = await GetReleaseDataAsync();
            var filteredData = allData.Where(d => d.MainFloraGroupID == groupId).ToList();

            _logger.LogDebug("Filtered release data by group {GroupId}: {Count} items", groupId, filteredData.Count);
            return filteredData;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to filter release data by group ID {GroupId}", groupId);
            return new List<SynopticPageConfiguration>();
        }
    }


}
