// 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.Linq;
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.
/// Fetches data from the backend API via IReleaseConfigurationService.
/// </summary>
public class ReleaseConfigRepository : IReleaseConfigRepository
{
    private readonly ILogger<ReleaseConfigRepository> _logger;
    private readonly IReleaseConfigurationService _releaseConfigurationService;
    private readonly IProjectMachineContext _projectMachineContext;

    private List<ReleaseDataConfiguration>? _cachedReleaseData;
    private DateTime? _lastReleaseDataLoad;
    private readonly TimeSpan _cacheExpiry = TimeSpan.FromMinutes(5);

    public ReleaseConfigRepository(
        ILogger<ReleaseConfigRepository> logger,
        IReleaseConfigurationService releaseConfigurationService,
        IProjectMachineContext projectMachineContext)
    {
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        _releaseConfigurationService = releaseConfigurationService ?? throw new ArgumentNullException(nameof(releaseConfigurationService));
        _projectMachineContext = projectMachineContext ?? throw new ArgumentNullException(nameof(projectMachineContext));
    }

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

            _logger.LogInformation("Loading release data from backend API");

            var projectCode = _projectMachineContext.SelectedProject.ProjectCode;
            var machineCode = _projectMachineContext.SelectedMachineCode;

            if (projectCode == null || string.IsNullOrWhiteSpace(machineCode))
            {
                _logger.LogWarning("Cannot load release data: project ID or machine code not available");
                return new List<ReleaseDataConfiguration>();
            }

            var releaseData = await _releaseConfigurationService.GetReleaseConfigurationAsync(
                projectCode, machineCode);

            _cachedReleaseData = releaseData;
            _lastReleaseDataLoad = DateTime.UtcNow;

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

    /// <summary>
    /// Loads release data filtered by group ID.
    /// </summary>
    public async Task<List<ReleaseDataConfiguration>> 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<ReleaseDataConfiguration>();
        }
    }
}
